Lua中的文件问题

我想了解如何删除特定文件的行?

例如:file.txt

  1. facebook
  2. twitter
  3. orkut
  4. msn

假设我想要删除第3行,那么文件将变为:

  1. facebook
  2. twitter
  3. msn

我不想仅仅删除这些行,还需要组织并避免在文件中出现空行!

点赞
用户501459
用户501459

加载文件内容,使用内存操作它们,然后将新的内容写回文件。

在这种情况下,你可以使用 files.lines 逐行加载文件内容,把你想要的存储到数组中,而不包括你不想要的内容,然后使用 table.concat 将数组转换成字符串。

2015-10-23 06:38:28
用户2689623
用户2689623

通过匹配字符串查找特定项:

function func(file, toDelete)
    local t = {}
    local tt = {}
    for line in io.lines(file) do
            table.insert(t, line)
    end

    for c, r in pairs(t) do
            if string.sub(r, 4) ~= toDelete then
                    table.insert(tt, string.sub(r, 4))
            end
    end

    local nfile = io.open(file, "w+")

    for a, b in pairs(tt) do
            nfile:write(a .. ". " .. b .. "\n")
    end
end

或者通过查找数字来查找:

function func(file, num)
    local t = {}
    local tt = {}
    for line in io.lines(file) do
            table.insert(t, line)
    end

    for c, r in pairs(t) do
            if c ~= num then
                    table.insert(tt, string.sub(r, 4))
            end
    end

    local nfile = io.open(file, "w+")

    for a, b in pairs(tt) do
            nfile:write(a .. ". " .. b .. "\n")
    end
end

注意:这将覆盖原始文件!

编辑: 对于上面的示例而言,如果不在前面添加数字,无需替换字符串。

2015-10-23 13:45:12