【问题标题】:Check if a file exists with Lua使用 Lua 检查文件是否存在
【发布时间】:2011-06-26 20:00:57
【问题描述】:

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

【问题讨论】:

  • @tonio - 我想更多的是lua.org/pil/21.2.html
  • @Liutauras 甚至接近真正的答案。我只对so进行了快速检查
  • 嗨,谢谢您的快速响应。我正在做:assert(io.input(fileName), "Error opening file") 但是当我给出一个虚拟文件名时,我没有收到错误消息:"Error opening file"。我得到的消息是:“'input' 的错误参数 #1(/pfrm2.0/share/lua/5.1/db/fake.dbdl:没有这样的文件或目录)”有什么想法吗?
  • Yoni,我知道你刚刚加入 SO。欢迎。几件事可提。 1)不要用一个新问题来回答你自己的问题。 2)尝试四处搜索(谷歌是你的朋友)以获取更多信息,只有当你完全被困在这里时才问。我相信这会让你成为一个更好的开发者。

标签: file-io lua file-exists


【解决方案1】:

试试

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

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

【讨论】:

  • 注意:如果文件是目录,此方法返回false
【解决方案2】:

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

【讨论】:

  • LuaFileSystem 也适用于 Windows。使用lfs.attributes(path,'mode')
【解决方案3】:

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

if os.isfile(path) then
    ...
end

【讨论】:

  • 这不是官方功能,是premake的功能
  • @Konrad 啊。我的错。 premake 是我使用 lua 的全部。 :(
  • 没问题的朋友
【解决方案4】:

我会从here引用我自己

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

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

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

玩得开心!

【讨论】:

  • 如何处理来自 os.rename 的有关重命名只读文件的错误?
  • 简单地从 lua 打开文件有什么风险?
  • @carpii 如果你试图打开一个锁定的文件并从中读取它可能会导致错误(你仍然想知道它是否是一个文件)。目录也是如此(如果主机支持目录锁定)。
  • @HenrikErlandsson 你是什么意思?对于“坏蛋错误”,我并不是说您可以通过代码修复。但是,AFAIK 您可以使用 pcall 来捕获它们。处理可能很复杂,并且可能会返回无意义的错误消息。
【解决方案5】:

为了完整起见:您也可以使用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

【讨论】:

【解决方案6】:

如果你愿意使用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,则该文件肯定存在。

【讨论】:

    【解决方案7】:

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

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

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

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

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

    【讨论】:

    • 这会打开一个短暂可见的控制台窗口,所以我建议不要这样做。
    【解决方案8】:

    Lua 5.1:

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

    【讨论】:

      【解决方案9】:

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

      【讨论】:

        【解决方案10】:

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

        然后在 Lua 中执行:

        require 'paths'
        
        if paths.filep('your_desired_file_path') then
            print 'it exists'
        else
            print 'it does not exist'
        end
        

        【讨论】:

          【解决方案11】:

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

          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.open 如果无法打开文件,则返回nil。作为旁注,这就是为什么它经常与assert 一起使用以在无法打开给定文件时产生有用的错误消息。例如:

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

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

          【讨论】:

            【解决方案12】:

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

            来自pathsofficial document

            paths.filep(路径)

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

            paths.dirp(路径)

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

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

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

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

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

            【讨论】:

              【解决方案13】:

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

              【讨论】:

                【解决方案14】:

                做这样的事情怎么样?

                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
                

                【讨论】:

                • 我收到'[[' is not recognized as an internal or external command, operable program or batch file.
                • 它在我的 unix 机器上工作。您使用的是什么操作系统? type [[ 应该说[[ is a shell keyword
                • @RakibFiha 他根据错误消息使用 windows,它在我的 Linux 机器上工作
                【解决方案15】:
                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')
                

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

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2013-01-14
                  • 2017-03-26
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-07-19
                  • 1970-01-01
                  相关资源
                  最近更新 更多