Lua中读取txt文件

一个简单的问题。我有一个文件 test.txt,它位于 userPath().."/log/test.txt 目录下,有15行 我希望读取第一行并删除第一行,并且最终该文件将剩下14行。

点赞
用户12568711
用户12568711

```lua
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行。

2020-08-24 18:00:06