2013-05-03 141 views
3

您可以在lua中复制文件吗?这可能吗? 您可能会认为只是将“设备”插入到新文件中,然而,这会在每个循环中创建一个新字符串 - 我没有在此代码段中包含一个循环。将csv文件复制到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 

回答

11

有很多方法可以做到这一点。

如果该文件是足够小,你可以阅读整个事情到一个字符串,并写入字符串到另一个文件:

infile = io.open("temp.csv", "r") 
instr = infile:read("*a") 
infile:close() 

outfile = io.open("log.csv", "w") 
outfile:write(instr) 
outfile:close() 

您也可以调用你的壳里做拷贝,尽管这为特定平台:

os.execute("cp temp.csv log.csv") 
+0

谢谢你,那是一个好主意 – kevintdiy 2013-05-03 22:35:10

1

第一个答案有一个简单的错误,这是

infile = io.open("temp.csv", "a") 

它应该在“阅读模式”而不是“追加”模式下打开它,所以让我们这样修复它

infile = io.open("temp.csv", "r") 

它会很好地工作。

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

不应该打开的文件被关闭的地方? – kikito 2014-03-03 16:51:21

+1

我自己回答:“ltn12.source.file”和“sink.file”在完成时自动关闭文件。 – kikito 2014-03-03 16:53:14

相关问题