How can i check if a file exists using lua?
如何使用lua检查文件是否存在?
9 个解决方案
#1
86
Try
试一试
function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
but note that this code only tests whether the file can be opened for reading.
但是请注意,此代码只测试文件是否可以打开读取。
#2
5
Using plain Lua, the best you can do is see if a file can be opened for read, as per LHF. This is almost always good enough. But if you want more, load the Lua POSIX library and check if posix.stat(
path)
returns non-nil
.
使用简单的Lua,您能做的最好的事情是看一个文件是否可以被打开来读取,如LHF。这几乎总是足够好。但是如果您想要更多,加载Lua POSIX库并检查POSIX .stat(path)是否返回非nil。
#3
4
I will quote myself from here
我在这里引用我自己的话。
I use these (but I actually check for the error):
我使用这些(但实际上我检查了错误):
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) will rename name1 to name2. Use the same name and nothing should change (except there is a badass error). If everything worked out good it returns true, else it returns nil and the errormessage. If you dont want to use lfs you cant differentiate between files and directories without trying to open the file (which is a bit slow but ok).
操作系统。rename(name1, name2)会将name1重命名为name2。使用相同的名称,没有任何更改(除非有一个badass错误)。如果一切顺利,它返回true,否则返回nil和errormessage。如果你不想使用lfs,你就不能在不打开文件的情况下区分文件和目录(这有点慢,但是可以)。
So without LuaFileSystem
所以没有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
It looks shorter, but takes longer... Also open a file is a it risky
它看起来更短,但需要更长的时间……同样打开一个文件是有风险的。
Have fun coding!
有有趣的编码!
#4
3
For sake of completeness: You may also just try your luck with path.exists(filename)
. I'm not sure which Lua distributions actually have this path
namespace (update: Penlight), but at least it is included in Torch:
为了完整性起见:您也可以尝试使用路径的运气。存在(文件名)。我不确定哪个Lua发行版实际上有这个路径名称空间(更新: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)
tells me that its source is in torch/install/share/lua/5.1/pl/path.lua
and it is implemented as follows:
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
#5
2
If you are willing to use lfs
, you can use lfs.attributes
. It will return nil
in case of error:
如果您愿意使用lfs,您可以使用lfs.attributes。如果出现错误,它将返回nil:
require "lfs"
if lfs.attributes("non-existing-file") then
print("File exists")
else
print("Could not get attributes")
end
Although it can return nil
for other errors other than a non-existing file, if it doesn't return nil
, the file certainly exists.
虽然它可以为其他错误返回nil,但如果它不返回nil,那么该文件肯定存在。
#6
1
I use:
我使用:
if os.isfile(path) then
...
end
I'm using LUA 5.3.4.
我使用LUA 5.3.4。
#7
0
You can also use the 'paths' package. Here's the link to the package
您还可以使用“路径”包。这是这个包裹的链接。
Then in Lua do:
然后在Lua中做的事:
require 'paths'
if paths.filep('your_desired_file_path') then
print 'it exists'
else
print 'it does not exist'
end
#8
0
An answer which is windows only checks for files and folders, and also requires no additional packages. It returns true
or false
.
答案是windows只检查文件和文件夹,也不需要额外的包。它返回真或假。
io.popen("if exist "..PathToFileOrFolder.." (echo 1)"):read'*l'=='1'
io.popen(...):read'*l' - executes a command in the command prompt and reads the result from the CMD stdout
popen(…):读取'*l' -在命令提示符中执行命令,并读取CMD stdout的结果。
if exist - CMD command to check if an object exists
如果存在- CMD命令来检查一个对象是否存在。
(echo 1) - prints 1 to stdout of the command prompt
(echo 1) -从命令提示符中打印1到stdout。
#9
-6
IsFile = function(path)
print(io.open(path or '','r')~=nil and 'File exists' or 'No file exists on this path: '..(path=='' and 'empty path entered!' or (path or 'arg "path" wasn\'t define to function call!')))
end
IsFile()
IsFile('')
IsFIle('C:/Users/testuser/testfile.txt')
Looks good for testing your way. :)
看起来很适合测试你的方式。:)
#1
86
Try
试一试
function file_exists(name)
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
but note that this code only tests whether the file can be opened for reading.
但是请注意,此代码只测试文件是否可以打开读取。
#2
5
Using plain Lua, the best you can do is see if a file can be opened for read, as per LHF. This is almost always good enough. But if you want more, load the Lua POSIX library and check if posix.stat(
path)
returns non-nil
.
使用简单的Lua,您能做的最好的事情是看一个文件是否可以被打开来读取,如LHF。这几乎总是足够好。但是如果您想要更多,加载Lua POSIX库并检查POSIX .stat(path)是否返回非nil。
#3
4
I will quote myself from here
我在这里引用我自己的话。
I use these (but I actually check for the error):
我使用这些(但实际上我检查了错误):
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) will rename name1 to name2. Use the same name and nothing should change (except there is a badass error). If everything worked out good it returns true, else it returns nil and the errormessage. If you dont want to use lfs you cant differentiate between files and directories without trying to open the file (which is a bit slow but ok).
操作系统。rename(name1, name2)会将name1重命名为name2。使用相同的名称,没有任何更改(除非有一个badass错误)。如果一切顺利,它返回true,否则返回nil和errormessage。如果你不想使用lfs,你就不能在不打开文件的情况下区分文件和目录(这有点慢,但是可以)。
So without LuaFileSystem
所以没有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
It looks shorter, but takes longer... Also open a file is a it risky
它看起来更短,但需要更长的时间……同样打开一个文件是有风险的。
Have fun coding!
有有趣的编码!
#4
3
For sake of completeness: You may also just try your luck with path.exists(filename)
. I'm not sure which Lua distributions actually have this path
namespace (update: Penlight), but at least it is included in Torch:
为了完整性起见:您也可以尝试使用路径的运气。存在(文件名)。我不确定哪个Lua发行版实际上有这个路径名称空间(更新: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)
tells me that its source is in torch/install/share/lua/5.1/pl/path.lua
and it is implemented as follows:
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
#5
2
If you are willing to use lfs
, you can use lfs.attributes
. It will return nil
in case of error:
如果您愿意使用lfs,您可以使用lfs.attributes。如果出现错误,它将返回nil:
require "lfs"
if lfs.attributes("non-existing-file") then
print("File exists")
else
print("Could not get attributes")
end
Although it can return nil
for other errors other than a non-existing file, if it doesn't return nil
, the file certainly exists.
虽然它可以为其他错误返回nil,但如果它不返回nil,那么该文件肯定存在。
#6
1
I use:
我使用:
if os.isfile(path) then
...
end
I'm using LUA 5.3.4.
我使用LUA 5.3.4。
#7
0
You can also use the 'paths' package. Here's the link to the package
您还可以使用“路径”包。这是这个包裹的链接。
Then in Lua do:
然后在Lua中做的事:
require 'paths'
if paths.filep('your_desired_file_path') then
print 'it exists'
else
print 'it does not exist'
end
#8
0
An answer which is windows only checks for files and folders, and also requires no additional packages. It returns true
or false
.
答案是windows只检查文件和文件夹,也不需要额外的包。它返回真或假。
io.popen("if exist "..PathToFileOrFolder.." (echo 1)"):read'*l'=='1'
io.popen(...):read'*l' - executes a command in the command prompt and reads the result from the CMD stdout
popen(…):读取'*l' -在命令提示符中执行命令,并读取CMD stdout的结果。
if exist - CMD command to check if an object exists
如果存在- CMD命令来检查一个对象是否存在。
(echo 1) - prints 1 to stdout of the command prompt
(echo 1) -从命令提示符中打印1到stdout。
#9
-6
IsFile = function(path)
print(io.open(path or '','r')~=nil and 'File exists' or 'No file exists on this path: '..(path=='' and 'empty path entered!' or (path or 'arg "path" wasn\'t define to function call!')))
end
IsFile()
IsFile('')
IsFIle('C:/Users/testuser/testfile.txt')
Looks good for testing your way. :)
看起来很适合测试你的方式。:)