Lua - 如何从 .csv 文件中删除空行或在处理时跳过它们?

我有一个 .csv 文件,它偶尔会有一个空行,这会导致我的脚本崩溃。我已经尝试了几种在处理时‘跳过’或将整个 csv 文件重新写入时不包括空行的方法(这两种方法都是我需要的选项)。

在 uniqueprotocsv.csv 中的示例数据

protocol; D; S; F
RC5; 10; -1; 12
RECS80; 5; -1; 13

MCE; 4; 15; 12
NEC1; 184; -1; 157
NEC; 184; -1; 157
NECx; 44; 44; 30
NECx; 44; 44; 163

NEC1; 4; -1; 8
Akai; 1; -1; 5
Sony12; 1; -1; 21

我目前的‘即时’代码尝试如下,但它仍然会出错..

local file = assert(io.open("uniqueprotocsv.csv", "r"))
    for line in file:lines() do
        if line == nil or line == "" then break
            local protocol, D, S, F = line:match("%s*(.-);%s*(.-);%s*(.-);%s*(.*)")
            local command = string.format(irptrans.. 'render --pronto --nameengine "{D='..tostring(D)..', S='..tostring(S)..', F='..tostring(F)..'}" '..tostring(protocol))
            print(command)
            local handle = assert(io.popen(command))
         end
    handle:close()

而这是我一直在努力工作的代码,我可以运行该代码来删除整个文件中的空行,同时找到源文件中的唯一行。从而消除了‘即时’处理的需要。

local csv = assert(io.open("protocsvfile.csv", "r"))
local uniquecsv = assert(io.open("uniqueprotocsv.csv", "a"))
local lines = {}
for line in csv:lines() do
 if line ~= nil or line ~= "" then
  if not lines[line] then
    --print(line)
    uniquecsv:write(line .. "\n")
  end
end
end

任何帮助都将不胜感激
点赞
用户12243315
用户12243315

你需要使用 and 而不是 or

local csv = assert(io.open("protocsvfile.csv", "r"))
local uniquecsv = assert(io.open("uniqueprotocsv.csv", "a"))
local lines = {}
for line in csv:lines() do
    if line ~= nil and line ~= "" then
        if not lines[line] then
            --print(line)
            uniquecsv:write(line .. "\n")
        end
    end
end
2021-03-22 14:48:27