需要编写一些文件,然后打开它进行读取并将一些行写入另一个文件 - 所有这些都在一个脚本中。 我的问题是,我:
在读取模式下打开file1(file1 = io.open(" my_file.txt"," r"))
在写入模式下打开file2(file2 = io.open(" my_changed_file.txt"," w"))
将更改的内容从file1写入file2
在读取模式下打开file2(尝试打开为file3 = io.open(" my_changed_file.txt"," r"))并从中打印一些行例如
我尝试了几种方法,比如file2:flush()或file2:close()并在我写完后重新打开,但是当我想打印一些行时它总是返回nil
file1=io.open("my_file.txt","r")
file2=io.open("my_changed_file.txt","w")
for line in file1:lines() do
file2:write(line.."changes")
end
file2:flush()
file3=io.open("my_changed_file.txt","r")
--write several lines to another file or something
--(need to combine changed lanes from file2 and original lines from file1 based on my key)
答案 0 :(得分:3)
我已经在Lua 5.1,5.2和5.3中对您的脚本进行了微小的更改,并且它在所有这些版本中都按预期工作。我的脚本位于下方,有一项更改可能很重要:write
不会像print
那样添加新行,因此如果您希望输出为自己,可能需要自行添加在不同的路线上:
local file1=io.open("my_file.txt","r")
local file2=io.open("my_changed_file.txt","w")
for line in file1:lines() do
file2:write(line.."changes\n")
end
file2:close()
local file3=io.open("my_changed_file.txt","r")
print(file3)
for line in file3:lines() do print(line) end