检查Lua是否存在文件

Yon*_*oni 63 file-io lua file-exists

如何使用Lua检查文件是否存在?

lhf*_*lhf 102

尝试

function file_exists(name)
   local f=io.open(name,"r")
   if f~=nil then io.close(f) return true else return false end
end
Run Code Online (Sandbox Code Playgroud)

但请注意,此代码仅测试是否可以打开文件进行读取.

  • 没有比男人本人更好的答案来源. (18认同)
  • 注意:如果文件是目录,该方法返回 false (4认同)

Nor*_*sey 7

使用普通Lua,您可以做的最好的事情是查看是否可以打开文件进行读取,如LHF所示.这几乎总是足够好.但是如果你想要更多,请加载Lua POSIX库并检查posix.stat(路径是否)返回非nil.

  • [LuaFileSystem](http://keplerproject.github.io/luafilesystem)也适用于Windows.使用`lfs.attributes(path,'mode')` (3认同)

rub*_*o77 7

卢阿 5.1:

function file_exists(name)
   local f = io.open(name, "r")
   return f ~= nil and io.close(f)
end
Run Code Online (Sandbox Code Playgroud)


tDw*_*wtp 5

我会从这里引用自己的话

我使用这些(但实际上我检查错误):

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
Run Code Online (Sandbox Code Playgroud)

os.rename(name1,name2)将name1重命名为name2.使用相同的名称,不应该更改任何内容(除了有一个badass错误).如果一切顺利,它返回true,否则返回nil和errormessage.如果您不想使用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
Run Code Online (Sandbox Code Playgroud)

它看起来更短,但需要更长时间......同时打开文件是有风险的

玩得开心!

  • 如何处理有关重命名只读文件的 os.rename 错误? (2认同)

Rom*_*rio 5

如果你愿意用lfs,就可以用lfs.attributesnil如果出现错误,它将返回:

require "lfs"

if lfs.attributes("non-existing-file") then
    print("File exists")
else
    print("Could not get attributes")
end
Run Code Online (Sandbox Code Playgroud)

尽管它可以返回除nil不存在文件之外的其他错误,但如果它不返回nil,则该文件肯定存在。


Jes*_*olm 5

如果您使用的是Premake和LUA版本5.3.4:

if os.isfile(path) then
    ...
end
Run Code Online (Sandbox Code Playgroud)

  • 这不是官方函数,它是 premake 的函数 (2认同)