我想tile自己解释了我如何访问这些文件并读取和写入它们?这就是我的代码看起来像
local openFile = assert(io.open(wasd_ ,"r")) -- wasd_ is the .txt file I want to open
local t = openFile:read("r") -- read the file
我不确定是否在代码的第一行中如果我关闭替换";wasd_;用";"wasd_txt";或文件路径(即,用类似的东西替换wasd_-->C:\users/stuff/blah/thing/wasd_(非常感谢蚂蚁的帮助
根据文档:
local Filename = "wasd_.txt"
local File = io.open(Filename, "r")
local FileContent = File:read("*all")
File:close()
该文件将根据当前目录%CD%
打开。如果您当前的目录是C:test
,那么打开的文件将是C:testwasd_.txt
。如果你想找到另一个文件,你可以指定完整的路径C:usersstuffblahthingwasd_.txt
如果您愿意,可以一次完成所有操作;Lua允许这样做,但当你一次一行地进行编辑时,你可以更好地控制编辑;以防您需要在某些行上使用某些编辑。写入新文件也更安全,因此您仍然有原始文件,可以进行比较并在需要时重试。
逐行,保持原始,写入新文本
local path = 'C:/users/stuff/blah/thing/wasd_.txt' -- wasd_ is the .txt file I want to open
local newpath = path :sub( 1, -5 ) ..'new.txt' -- C:/users/stuff/blah/thing/wasd_new.txt
local iput = assert( io.input( path ) )
local oput = assert( io.output( newpath ) )
local linenum = 0 -- used as a counter
while true do
linenum = linenum +1
local line = iput :read()
if line == nil then break end -- break out of loop if there's nothing else to read
local newline, _ = line :gsub( 'this', 'that' ) -- do your changes here
if linenum == 1 then newline = 'HEADER: ' ..newline end -- example of specific line edit
oput :write( linenum ..' ' ..newline ..'n' ) -- read() line strips newline char, so add it back
end
iput :close()
oput :close()
如果不需要的话,你可以去掉linenum
的所有实例,但我强烈建议你使用两个单独的read&写文件,至少在你感到舒服之前,它正是在做你想要的事情,并且没有错误。