【问题标题】:Read file txt with lua用lua读取文件txt
【发布时间】:2020-12-13 08:48:50
【问题描述】:

一个简单的问题。我在userPath().."/log/test.txt 有 1 个文件 test.txt,第 15 行 我希望阅读第一行并删除第一行,最后用 14 行文件 test.txt

【问题讨论】:

标签: file lua


【解决方案1】:

local iFile = 'the\\path\\test.txt'

local contentRead = {}
local i = 1

file = io.open(iFile, 'r')

for lines in file:lines() do
    if i ~= 1 then
        table.insert(contentRead, lines)
    else
        i = i + 1 -- this will prevent us from collecting the first line
        print(lines) -- just in case you want to display the first line before deleting it
    end
end

io.close(file)

local file = io.open(iFile, 'w')

for _,v in ipairs(contentRead) do
    file:write(v.."\n")
end

io.close(file)

肯定有其他方法可以简化这个,但基本上我在代码中所做的是:

  1. 以阅读模式打开文件,并将除第一行以外的所有文本行存储在表格contentRead

  2. 我再次打开文件,但这次是在写入模式下,导致文件的全部内容被擦除,然后,我重写了文件中存储在表contentRead中的所有内容。

因此,文件的第一行被“删除”,只剩下其他 14 行

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    相关资源
    最近更新 更多