使用Lua将一些文本附加到文件的第一行

时间:2016-03-20 17:04:55

标签: lua

如何使用Lua将一些文本添加到文件的第一行?

out = io.open('file.txt}','a')
out:write('Hello world. ')
out:write('This is different')
io.close(out)

我只知道如何使用上面的代码将内容附加到文件中。

2 个答案:

答案 0 :(得分:2)

创建一个新文件,插入你的东西。然后附加旧文件的内容。完成后,将旧文件替换为新文件。

一般情况下,您不会预先(或插入)文件。在整个概念中没有任何意义。您将文件数据保存到群集中。他们有一个开始和一个给定的大小。 因此,大多数编程语言都没有提供任何手段。

想象一下,一个文件保存在存储桶(集群)中。水代表数据。你从下到上填充1个桶。然后是第二个,依此类推。当您在文件中附加内容时,只需在上一个桶中添加水即可。如果已满,则添加另一个桶并从上到下填充。

现在尝试在文件中添加一些东西,半个桶大小。您的第一个存储桶已满,因此您可以在该行前添加一个存储桶。你可以从顶部到中间填充新的水桶吗?没有。 你可以从底部到中间填充它。但是现在你的文件中有一个半桶的差距。

它以某种方式工作。我想不出一个更好的例子atm。

答案 1 :(得分:1)

您可以将文本添加到文件的第一行,如此。

-- Open the file in r mode (don't modify file, just read)
local out = io.open('file.txt', 'r')

-- Fetch all lines and add them to a table
local lines = {}
for line in f:lines() do
    table.insert(lines, line)
end

-- Close the file so that we can open it in a different mode
out:close()

-- Insert what we want to write to the first line into the table
table.insert(lines, 1, "<what you want to write to the first line>\n")

-- Open temporary file in w mode (write data)
-- Iterate through the lines table and write each line to the file
local out = io.open('file.tmp.txt', 'w')
for _, line in ipairs(lines) do
    out:write(line)
end
out:close()

-- At this point, we should have successfully written the data to the temporary file

-- Delete the old file
os.remove('file.txt')

-- Rename the new file
os.rename('file.tmp.txt', 'file.txt')

我希望这证明是有用的!如果它不能按你的意愿工作,请告诉我。

这是关于IO库的一个很好的文档,供进一步参考。 http://lua-users.org/wiki/IoLibraryTutorial

相关问题