Check if a file exists with Lua

File IoLuaFile Exists

File Io Problem Overview


How can I check if a file exists using Lua?

File Io Solutions


Solution 1 - File Io

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.

Solution 2 - File Io

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.

Solution 3 - File Io

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).

So without 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!

Solution 4 - File Io

If you're using Premake and LUA version 5.3.4:

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

Solution 5 - File Io

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:

$ 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:

--- 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

Solution 6 - File Io

If you are willing to use lfs, you can use lfs.attributes. It will return nil in case of error:

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.

Solution 7 - File Io

An answer which is windows only checks for files and folders, and also requires no additional packages. It returns true or false.

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

> if exist - CMD command to check if an object exists

> (echo 1) - prints 1 to stdout of the command prompt

Solution 8 - File Io

Lua 5.1:

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

Solution 9 - File Io

An answer which is windows only checks for files and folders, and also requires no additional packages. It returns true or false.

Solution 10 - File Io

You can also use the 'paths' package. Here's the link to the package

Then in Lua do:

require 'paths'

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

Solution 11 - File Io

Not necessarily the most ideal as I do not know your specific purpose for this or if you have a desired implementation in mind, but you can simply open the file to check for its existence.

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 returns nil if it fails to open the file. As a side note, this is why it is often used with assert to produce a helpful error message if it is unable to open the given file. For instance:

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

If the file hello.txt does not exist, you should get an error similar to stdin:1: hello.txt: No such file or directory.

Solution 12 - File Io

For library solution, you can use either paths or path.

From the official document of paths:

> paths.filep(path) > > Return a boolean indicating whether path refers to an existing file. > > paths.dirp(path) > > Return a boolean indicating whether path refers to an existing directory.

Although the names are a little bit strange, you can certainly use paths.filep() to check whether a path exists and it is a file. Use paths.dirp() to check whether it exists and it is a directory. Very convenient.

If you prefer path rather than paths, you can use path.exists() with assert() to check the existence of a path, getting its value at the same time. Useful when you are building up path from pieces.

prefix = 'some dir'

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

If you just want to check the boolean result, use path.isdir() and path.isfile(). Their purposes are well-understood from their names.

Solution 13 - File Io

How about doing something like this?

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

Solution 14 - File Io

If you use LOVE, you can use the function love.filesystem.exists('NameOfFile'), replacing NameOfFile with the file name. This returns a Boolean value.

Solution 15 - File Io

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. :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYoniView Question on Stackoverflow
Solution 1 - File IolhfView Answer on Stackoverflow
Solution 2 - File IoNorman RamseyView Answer on Stackoverflow
Solution 3 - File IotDwtpView Answer on Stackoverflow
Solution 4 - File IoJesse ChisholmView Answer on Stackoverflow
Solution 5 - File Iobluenote10View Answer on Stackoverflow
Solution 6 - File IoRomárioView Answer on Stackoverflow
Solution 7 - File IoWalyKuView Answer on Stackoverflow
Solution 8 - File Iorubo77View Answer on Stackoverflow
Solution 9 - File IoIMBEASTView Answer on Stackoverflow
Solution 10 - File IoAmirView Answer on Stackoverflow
Solution 11 - File IoPersonageView Answer on Stackoverflow
Solution 12 - File IocgsdfcView Answer on Stackoverflow
Solution 13 - File IoRakib FihaView Answer on Stackoverflow
Solution 14 - File IoHyperBridView Answer on Stackoverflow
Solution 15 - File IoArchinamonView Answer on Stackoverflow