Loops 在循环中写入时如何在文件名中添加数字?
加速度记录在result.txt中,但我只想在result中记录1个结果 我想在result_1.txt中记录下一个结果,然后是result_2.txt,result_3.txt 如何在1个txt文件中记录1个结果 这是我的密码Loops 在循环中写入时如何在文件名中添加数字?,loops,lua,Loops,Lua,加速度记录在result.txt中,但我只想在result中记录1个结果 我想在result_1.txt中记录下一个结果,然后是result_2.txt,result_3.txt 如何在1个txt文件中记录1个结果 这是我的密码 local filename = "result.txt" local file = io.open(filename, "a") for i=1, 1000 do sim:stepForward() local p = ship.rb:getAc
local filename = "result.txt"
local file = io.open(filename, "a")
for i=1, 1000 do
sim:stepForward()
local p = ship.rb:getAcceleration():z()
file:write(string.format("%d\n",p))
end
file:close()
要输出的每个文件都需要不同的文件处理程序 为简单起见,假设文件名以
result_1.txt
开头:
for i = 1, 1000 do
local filename = "result_" + tostring(i) + ".txt"
local file = io.open(filename, "a")
-- write to file
file:close()
end
要将每个文件保存到不同的文件,需要分别打开和关闭每个文件。可以编写一个函数来为您执行此操作
saveData = function ( data, path )
local f = io.open(path, 'a')
f:write(data)
f:close()
end
然后你可以打电话
saveData(string.format("%d\n",p), 'results_1.txt')
现在,我们只需使用一个循环并将数字与字符串连接起来,就可以将它们按升序排列
for i = 1, 10, 1 do
local path = 'results_'..i..'.txt'
saveData(<insert data here>, path)
end
data = { <insert data here>, ... }
for i, v in ipairs(data) do
local path = 'results_'..i..'.txt'
saveData(v, path)
end