我如何使用Lua检查文件是否存在?
我如何使用Lua检查文件是否存在?
尝试
function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
但请注意,这段代码只是测试文件是否能够被打开以供读取。
使用纯Lua,你最好的选择是按照LHF的建议检查文件是否可以被读取。这几乎总是足够的。但如果你需要更多的功能,请加载Lua POSIX库并检查posix.stat(
路径)
是否返回非nil
值。
lfs.attributes(path,'mode')
函数。 - Lorenzo Donati support Ukrainefunction file_exists(name)
local f = io.open(name, "r")
return f ~= nil and io.close(f)
end
我会引用自己在这里的内容:
我使用以下代码(但实际上我会检查错误):
require("lfs")
-- no function checks for errors.
-- you should check for them
function isFile(name)
if type(name)~="string" then return false end
if not isDir(name) then
return os.rename(name,name) and true or false
-- note that the short evaluation is to
-- return false instead of a possible nil
end
return false
end
function isFileOrDir(name)
if type(name)~="string" then return false end
return os.rename(name, name) and true or false
end
function isDir(name)
if type(name)~="string" then return false end
local cd = lfs.currentdir()
local is = lfs.chdir(name) and true or false
lfs.chdir(cd)
return is
end
使用os.rename(name1, name2)命令可以将name1重命名为name2。如果两个名称相同,除非出现错误,否则不会发生任何更改。如果操作成功,则返回true;否则返回nil和错误信息。如果不想使用lfs,则无法区分文件和目录,除非尝试打开该文件(这可能有点慢,但还算可以)。
因此,在没有LuaFileSystem的情况下:
-- no require("lfs")
function exists(name)
if type(name)~="string" then return false end
return os.rename(name,name) and true or false
end
function isFile(name)
if type(name)~="string" then return false end
if not exists(name) then return false end
local f = io.open(name)
if f then
f:close()
return true
end
return false
end
function isDir(name)
return (exists(name) and not isFile(name))
end
看起来更短,但需要更长时间... 同时打开文件也有一定的风险
愉快地进行编码吧!
如果您正在使用 Premake 和 LUA 版本 5.3.4:
if os.isfile(path) then
...
end
lfs
,可以使用lfs.attributes
。它将在出错的情况下返回nil
:require "lfs"
if lfs.attributes("non-existing-file") then
print("File exists")
else
print("Could not get attributes")
end
虽然它可能会对存在的文件以外的其他错误返回 nil
,但如果没有返回 nil
,则该文件肯定存在。
为了完整起见:您也可以尝试运行 path.exists(filename)
。我不确定哪些Lua发行版实际上具有此path
命名空间(更新:Penlight),但至少在Torch中包含了它:
$ th
______ __ | Torch7
/_ __/__ ________/ / | Scientific computing for Lua.
/ / / _ \/ __/ __/ _ \ | Type ? for help
/_/ \___/_/ \__/_//_/ | https://github.com/torch
| http://torch.ch
th> path.exists(".gitignore")
.gitignore
th> path.exists("non-existing")
false
debug.getinfo(path.exists)
告诉我它的源代码在 torch/install/share/lua/5.1/pl/path.lua
中,实现方式如下:
--- does a path exist?.
-- @string P A file path
-- @return the file path if it exists, nil otherwise
function path.exists(P)
assert_string(1,P)
return attrib(P,'mode') ~= nil and P
end
一个仅适用于Windows的答案检查文件和文件夹,也不需要额外的软件包。它将返回true
或false
。
io.popen("if exist "..PathToFileOrFolder.." (echo 1)"):read'*l'=='1'
io.popen(...):read'*l' - 在命令提示符中执行命令并从CMD标准输出读取结果
if exist - CMD命令用于检查对象是否存在
(echo 1) - 将1打印到命令提示符的标准输出
一个仅适用于Windows的答案检查文件和文件夹,并且不需要额外的软件包。它返回真或假。
require 'paths'
if paths.filep('your_desired_file_path') then
print 'it exists'
else
print 'it does not exist'
end