使用Lua检查文件是否存在。

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

原文链接 https://stackoverflow.com/questions/4990990

点赞
stackoverflow用户107090
stackoverflow用户107090

尝试

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

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

2011-02-14 11:26:12
stackoverflow用户483603
stackoverflow用户483603
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 = function(path)
print(io.open(path or '','r') ~= nil and '文件已存在' or '此路径上不存在文件:' .. (path == '' and '未输入空路径!' or (path or 'arg "path" wasn\'t define to function call!')))
end

IsFile()
IsFile('')
IsFile('C:/Users/testuser/testfile.txt')
2011-02-14 12:13:56
stackoverflow用户41661
stackoverflow用户41661

使用纯 Lua,你所能做的最好的事情是检查一个文件是否可以被读取,如 LHF 所述。这几乎总是足够的。但如果你需要更多,加载 Lua POSIX 库 并检查 posix.stat( path ) 是否返回非 nil

2012-08-31 23:32:44
stackoverflow用户2764551
stackoverflow用户2764551

我将引用我自己的话这里

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

require("lfs")
--没有函数检查错误。
--你应该检查他们

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
        --注意,短评价是为了返回可能的nil而不是false
    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

--不使用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-07 21:09:41
stackoverflow用户1804173
stackoverflow用户1804173

为了完整起见:你也可以试试运气,使用 path.exists(filename)。我不确定哪些 Lua 发行版实际上有这个 path 命名空间( 更新Penlight),但至少它包含在 Torch 中:

$ th

  ______             __   |  Torch7
 /_  __/__  ________/ /   |  Lua 的科学计算平台。
  / / / _ \/ __/ __/ _ \  |  输入 ? 获取帮助
 /_/  \___/_/  \__/_//_/  |  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 中,并且其实现如下:

--- 判断一个路径是否存在。
-- @string P 文件路径。
-- @return 如果文件存在则返回文件路径,否则返回 nil。
function path.exists(P)
    assert_string(1,P)
    return attrib(P,'mode') ~= nil and P
end
2015-10-12 09:38:32
stackoverflow用户2507567
stackoverflow用户2507567

如果你想使用 lfs,你可以使用 lfs.attributes。如果出错,它将返回 nil

require "lfs"

if lfs.attributes("non-existing-file") then
    print("文件存在")
else
    print("无法获取属性")
end

尽管它可能会返回 nil,但也可能是其他错误导致的,而不仅仅是文件不存在的错误。如果它没有返回 nil,则该文件肯定存在。

2015-10-22 19:33:20
stackoverflow用户2838606
stackoverflow用户2838606

你也可以使用 paths 工具包。这里是该工具包的链接。

然后在 Lua 中,进行如下操作:

require 'paths'

if paths.filep('your_desired_file_path') then
    print 'it exists'
else
    print 'it does not exist'
end
2017-05-10 00:50:15
stackoverflow用户3507506
stackoverflow用户3507506

一个只适用于Windows的答案,检查文件和文件夹,并且不需要额外的软件包。它返回 truefalse

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

io.popen(...):read'*l' - 在命令提示符中执行命令并从CMD stdout读取结果

if exist - CMD命令以检查对象是否存在

(echo 1) - 将1打印到命令提示符的stdout中

2017-08-23 15:23:44
stackoverflow用户1456887
stackoverflow用户1456887

如果你正在使用 Premake 和 LUA 版本 5.3.4:

if os.isfile(path) then
    ...
end
2017-12-08 16:56:39
stackoverflow用户9922866
stackoverflow用户9922866

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

local function file_exists(filename)
    local file = io.open(filename, "r")
    if (file) then
        -- 如果成功打开文件,则关闭该文件。
        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:找不到文件或目录的错误。

2019-02-19 07:04:43
stackoverflow用户1069083
stackoverflow用户1069083

Lua 5.1:

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

将上面的 Lua 5.1 代码翻译成中文并且保留原本的 markdown 格式:

function file_exists(name)  -- 定义一个函数用于判断文件是否存在
   local f = io.open(name, "r")  -- 以只读方式打开文件
   return f ~= nil and io.close(f)  -- 如果文件存在则返回 true,否则返回 false
end
2019-02-19 21:35:57
stackoverflow用户8039762
stackoverflow用户8039762

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

paths官方文档中:

paths.filep(path)
返回一个布尔值,指示路径是否是一个现有的文件。

paths.dirp(path)
返回一个布尔值,指示路径是否是一个现有的目录。

虽然这些名称有点奇怪,但你可以使用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()。从它们的名称就可以理解它们的目的。

2019-04-04 08:04:47
stackoverflow用户9496100
stackoverflow用户9496100

如何做类似这样的事情?

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("嗨,文件存在")
else
  print("再见,文件不存在")
end
2019-08-19 08:47:25
stackoverflow用户12230942
stackoverflow用户12230942

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

2020-02-07 06:41:39
stackoverflow用户13571344
stackoverflow用户13571344

一个仅适用于 Windows 的答案检查文件和文件夹,也不需要额外的软件包。它返回 true 或 false。

2020-05-19 01:25:43
stackoverflow用户296559
stackoverflow用户296559

如果你和我一样只在 Linux、BSD 或其他 UNIX 类型的系统上使用,你可以使用以下代码:

function isDir(name)
    if type(name)~="string" then return false end
    return os.execute('if [ -d "'..name..'" ]; then exit 0; else exit 1; fi')
end

function isFile(name)
    if type(name)~="string" then return false end
    return os.execute('if [ -f "'..name..'" ]; then exit 0; else exit 1; fi')
end

实际上,以下代码甚至更好:

function isDir(name)
    if type(name)~="string" then return false end
    return os.execute('test -d '..name)
end

function isFile(name)
    if type(name)~="string" then return false end
    return os.execute('test -f '..name)
end

function exists(name)
    if type(name)~="string" then return false end
    return os.execute('test -e '..name)
end
2022-06-18 01:45:17