你能用lua复制一个文件吗?这可能吗? 您可能会认为只是将“devices”插入到新文件中,但是在每个循环中创建一个新字符串 - 我没有在此片段中包含该循环。
file = io.open("temp.csv", "a")
file:write(devices)
file = io.open("log.csv", "w")
file:write("")
if (count = 15) then
--copy "temp.csv" to "log.csv"
end
答案 0 :(得分:11)
有很多方法可以做到这一点。
如果文件足够小,您可以将整个内容读入字符串,并将字符串写入另一个文件:
infile = io.open("temp.csv", "r")
instr = infile:read("*a")
infile:close()
outfile = io.open("log.csv", "w")
outfile:write(instr)
outfile:close()
您也可以调用shell来执行复制,尽管这是特定于平台的:
os.execute("cp temp.csv log.csv")
答案 1 :(得分:3)
大多数Lua'ish的方式,但也许不是最有效的:
-- load the ltn12 module
local ltn12 = require("ltn12")
-- copy a file
ltn12.pump.all(
ltn12.source.file(assert(io.open("temp.csv", "rb"))),
ltn12.sink.file(assert(io.open("log.csv", "wb")))
)
在此之前,您还需要确保拥有LuaSocket,以获得简单的环境:
sudo luarocks install luasocket
还有更好的方法:
==== util.lua ====
-- aliases for protected environments
local assert, io_open
= assert, io.open
-- load the ltn12 module
local ltn12 = require("ltn12")
-- No more global accesses after this point
if _VERSION == "Lua 5.2" then _ENV = nil end
-- copy a file
local copy_file = function(path_src, path_dst)
ltn12.pump.all(
ltn12.source.file(assert(io_open(path_src, "rb"))),
ltn12.sink.file(assert(io_open(path_dst, "wb")))
)
end
return {
copy_file = copy_file;
}
===== main.lua ====
local copy_file = require("util").copy_file
copy_file("temp.csv", "log.csv")