You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua读取CSV脚本最后一行输出格式异常求助

Lua CSV解析最后一行输出格式错乱问题解决

问题描述

编写Lua脚本读取CSV文件并将每行解析为table时,发现最后一行输出格式异常,仅在循环的最后一行出现该问题,数据本身正确但打印时格式错乱。

核心代码

function split(s, delimiter)
    local result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end

function readCSV(filename)
    local file = io.open(filename, "r")
    if not file then
        error("Failed to open file: " .. filename)
    end

    local header = file:read()
    local headerArr = split(header, ",")
    print("length of headerArr: " .. #headerArr)
    for i, value in ipairs(headerArr) do
        print(i, value)
    end

    local data = {}

    for line in file:lines() do
        line = line:gsub("\n", ""):gsub("\r", "")
        print("line: " .. line)
        local valuesArr = split(line, ",")
        print("length of valuesArr: " .. #valuesArr)

        local entry = {}

        for i = 1, #valuesArr do
            print("headerArr[" .. i .. "]:" .. headerArr[i])
            print("valuesArr[" .. i .. "]:" .. valuesArr[i])
            print(string.format("headerArr[%d] key = '%s' , value = '%s'", i, headerArr[i], valuesArr[i]))
            print("-------------------------------------------------")
        end

        -- table.insert(data, entry)
    end

    file:close()

    return data
end

-- Usage example
local filename = "/Users/weijialiu/Downloads/FC 24 CT v24.1.1.4/FC_24_LE_ICONS.csv"
local data = readCSV(filename)

-- Print the data
for i, entry in ipairs(data) do
    for header, value in pairs(entry) do
        print(header .. ": " .. value)
    end
    print("--------------------")
end

异常表现

...
headerArr[1021]:runningcode2
valuesArr[1021]:0
headerArr[1021] key = 'runningcode2' , value = '0'

headerArr[1022]:modifier
valuesArr[1022]:2
headerArr[1022] key = 'modifier' , value = '2'

headerArr[1023]:gkhandling
valuesArr[1023]:9
headerArr[1023] key = 'gkhandling' , value = '9'

headerArr[1024]:eyecolorcode
valuesArr[1024]:2
' , value = '2' key = 'eyecolorcode

已尝试操作

  • 确认打印前字符串拼接逻辑正确
  • 检查CSV文件,确认无多余分隔符或换行符
  • 添加调试信息追踪数据处理流程

解决方案

1. 修复Header的换行符处理

问题根源在于Header行未清理回车符(\r):代码中仅对数据行做了换行符清理,但读取Header时直接用file:read()获取,未清理可能存在的\r字符。当Header最后一个字段带有\r时,打印该字符串会触发光标回到行首,后续内容会覆盖前面的输出,导致格式错乱。

修改Header读取代码:

local header = file:read()
-- 新增:清理Header中的换行/回车符
header = header:gsub("\n", ""):gsub("\r", "")
local headerArr = split(header, ",")

2. 优化Split函数(可选)

当前split函数在处理带引号的CSV字段时会失效(比如字段内容包含逗号),如果你的CSV存在这类场景,可以替换为更健壮的实现:

function splitCSVLine(s)
    local result = {}
    local inQuotes = false
    local current = ""
    for c in s:gmatch(".") do
        if c == '"' then
            inQuotes = not inQuotes
        elseif c == "," and not inQuotes then
            table.insert(result, current)
            current = ""
        else
            current = current .. c
        end
    end
    table.insert(result, current)
    return result
end

使用时将原split调用替换为splitCSVLine即可。

验证:修改后重新运行脚本,Header字段的\r被清理,打印时不会再出现光标回退,最后一行输出格式恢复正常。

内容的提问来源于stack exchange,提问作者Weijia Liu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 17:39:51