Lua文件串联
我试图将 lua 文件夹中的每个文件连接起来,将一堆日志编译成一个主日志并将其发送给某人。我使用 ifs 库迭代目录中的每个文件,然后读取所有文件并尝试将其附加到主文件中。
for name in lfs.dir("logs") do
if(name ~= "." and name ~= "..") then
local path = "logs/"..name
print (path)
local file=io.open(path,"R")
print "2"
local content = io.read("*all")
print "3"
io.close(file)
local f=io.open("log.csv","A")
file:write(content)
io.close(f)
end
end
有两个问题。 ifs 库返回“.”和其他文件名之前的“..”[是否有比 if 语句更好的方法来忽略这些文件名?] 使用我在这里找到的位: 如何从目录加载所有文件?
重要的问题是,当我测试文件时,我的命令提示符不断崩溃。它打印路径(一个好的路径),然后在到达“2”之前崩溃,我不知道为什么。该文件存在,我可以通过在另一个函数中向其添加行来操作它。
任何帮助将不胜感激。
I'm trying to concatenate every file in a folder in lua to compile a bunch of logs into one master log and send it off to someone. I'm using the ifs library to iterate through every file in a directory, then reading it all in and trying to append it to the master file.
for name in lfs.dir("logs") do
if(name ~= "." and name ~= "..") then
local path = "logs/"..name
print (path)
local file=io.open(path,"R")
print "2"
local content = io.read("*all")
print "3"
io.close(file)
local f=io.open("log.csv","A")
file:write(content)
io.close(f)
end
end
There are two issues.
The ifs library returns "." and ".." before the other file names [is there a better way to ignore these than an if statement?]
using the bit I found here: How to load all files from a directory?
The important issue is that my command prompt keeps crashing when I test the file. It prints the path (a good one), then it crashes before getting to the "2" and I'm not sure why. The file exists and I can manipulate it by adding lines to it in another function.
Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了避免检查
"."
和".."
您应该使用lfs.attributes
及其mode
字段查看每个项目是否是文件或目录(或其他内容)。您可能需要
file:read
而不是io.read
——这可能是导致“崩溃”的原因。我建议您使用
"r"
和"a+"
作为io.open
模式参数。哦,还有使用
f:write
来写入content
To avoid checking for
"."
and".."
you should uselfs.attributes
and itsmode
field to see if each item is a file or directory (or something else).Instead of
io.read
you probably wantfile:read
-- this might be the cause of your "crash."I suggest you use
"r"
and"a+"
for theio.open
mode arguments.Oh, and use
f:write
to writecontent