79

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

4

15 回答 15

116

尝试

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

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

于 2011-02-14T11:26:12.727 回答
7

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

于 2012-08-31T23:32:44.047 回答
6

如果您使用Premake和 LUA 5.3.4 版:

if os.isfile(path) then
    ...
end
于 2017-12-08T16:56:39.173 回答
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

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

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

玩得开心编码!

于 2014-02-07T21:09:41.233 回答
3

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

require "lfs"

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

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

于 2015-10-22T19:33:20.277 回答
3

一个答案是 windows 只检查文件和文件夹,也不需要额外的包。它返回truefalse

io.popen("if exist "..PathToFileOrFolder.." (echo 1)"):read'*l'=='1'

io.popen(...):read'*l' - 在命令提示符下执行命令并从 CMD 标准输出读取结果

如果存在- CMD 命令检查对象是否存在

(echo 1) - 将 1 打印到命令提示符的标准输出

于 2017-08-23T15:23:44.980 回答
3

为了完整起见:您也可以试试运气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
于 2015-10-12T09:38:32.763 回答
2

路亚 5.1:

function file_exists(name)
   local f = io.open(name, "r")
   return f ~= nil and io.close(f)
end
于 2019-02-19T21:35:57.663 回答
2

一个答案是 windows 只检查文件和文件夹,也不需要额外的包。它返回真或假。

于 2020-05-19T01:25:43.603 回答
1

您也可以使用“路径”包。是包的链接

然后在 Lua 中:

require 'paths'

if paths.filep('your_desired_file_path') then
    print 'it exists'
else
    print 'it does not exist'
end
于 2017-05-10T00:50:15.373 回答
0

不一定是最理想的,因为我不知道您为此的具体目的,或者您是否有想要的实现,但您可以简单地打开文件以检查它的存在。

local function file_exists(filename)
    local file = io.open(filename, "r")
    if (file) then
        -- Obviously close the file if it did successfully open.
        file:close()
        return true
    end
    return false
end

io.opennil如果无法打开文件,则返回。作为旁注,这就是为什么它经常用于在assert无法打开给定文件时产生有用的错误消息的原因。例如:

local file = assert(io.open("hello.txt"))

如果该文件hello.txt不存在,您应该会收到类似于stdin:1: hello.txt: No such file or directory.

于 2019-02-19T07:04:43.717 回答
0

对于库解决方案,您可以使用pathspath

来自官方paths文档:

路径.filep(路径)

返回一个布尔值,指示路径是否引用现有文件。

路径.dirp(路径)

返回一个布尔值,指示路径是否引用现有目录。

虽然名字有点奇怪,但是你当然可以用它paths.filep()来检查一个路径是否存在,它是一个文件。用于paths.dirp()检查它是否存在并且是一个目录。很方便。

如果您更喜欢path而不是paths,您可以使用path.exists()withassert()来检查路径是否存在,同时获取它的值。当您从碎片构建路径时很有用。

prefix = 'some dir'

filename = assert(path.exist(path.join(prefix, 'data.csv')), 'data.csv does not exist!')

如果您只想检查布尔结果,请使用path.isdir()and path.isfile()。从他们的名字可以很好地理解他们的目的。

于 2019-04-04T08:04:47.530 回答
0

做这样的事情怎么样?

function exist(file)
  local isExist = io.popen(
    '[[ -e '.. tostring(file) ..' ]] && { echo "true"; }')
  local isIt = isExist:read("*a")
  isExist:close()
  isIt = string.gsub(isIt, '^%s*(.-)%s*$', '%1')
  if isIt == "true" then
    return true
  end
  return false
end

if exist("myfile") then
  print("hi, file exists")
else
  print("bye, file does not exist")
end
于 2019-08-19T08:47:25.640 回答
0

如果你使用 LOVE,你可以使用函数love.filesystem.exists('NameOfFile'),替换NameOfFile为文件名。这将返回一个布尔值。

于 2020-02-07T06:41:39.557 回答
-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')

看起来很适合测试你的方式。:)

于 2011-02-14T12:13:56.640 回答