3

你可以在lua中复制文件吗?这可能吗?但是,您可能会认为只是将“设备”插入新文件中,这会在每个循环中创建一个新字符串 - 我没有包含在此代码段中的循环。

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
4

2 回答 2

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")
于 2013-05-03T21:55:59.210 回答
3

Most Lua'ish way to do it, but perhaps not most effective:

-- 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")))
)

Also before that you need to make sure you have LuaSocket, for a simple environment:

sudo luarocks install luasocket

Also even better way:

==== 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")
于 2014-01-07T13:16:10.133 回答