Check if file exists with Lua

How can I check if a file exists using Lua?

+63
file-io lua file-exists
Feb 14 '11 at 10:18
source share
13 answers

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 checks if the file can be opened for reading.

+102
Feb 14 '11 at 11:26
source share
β€” -

Using simple Lua, the best thing you can do is see if you can open the file for reading according to LHF. This is almost always good enough. But if you want more, download the Lua POSIX library and see if posix.stat( path ) returns nil .

+7
Aug 31 '12 at 23:32
source share

I will bring myself from here

I use these (but I really check for an 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 for the badass error). If everything works well, it returns true, otherwise it returns nil and errormessage. If you do not want to use lfs, you cannot distinguish between files and directories without trying to open the file (which is a bit slow but normal).

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 opening a file is risky

Have fun coding!

+5
Feb 07 '14 at 21:09
source share

If you are using Premake and LUA version 5.3.4:

 if os.isfile(path) then ... end 
+5
Dec 08 '17 at 16:56 on
source share

For completeness: you can 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's included in the 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 PA 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 
+3
12 Oct '15 at 9:38
source share

If you want 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 may return nil for errors other than a nonexistent file, if it does not return nil , the file certainly exists.

+3
Oct 22 '15 at 19:33
source share

The answer, which is only windows, checks files and folders, and also does not require additional packages. It returns true or false .

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

io.popen (...): read '* l' - executes a command on the command line and reads the result from CMD stdout

if exists , a CMD command to verify the existence of an object

(echo 1) - prints 1 to standard command line output

+2
Aug 23 '17 at 15:23
source share

You can also use the "paths" package. Here is a 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 
+1
May 10 '17 at a.m.
source share

Not necessarily the most ideal, as I don’t know your specific purpose for this or if you mean the desired implementation, but you can simply open the file to check 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 the file cannot be opened. By the way, that is why it is often used with assert to create a useful error message if it cannot open this file. For example:

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

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

0
Feb 19 '19 at 7:04
source share

Lua 5.1:

 function file_exists(name) local f = io.open(name, "r") return f ~= nil and io.close(f) end 
0
Feb 19 '19 at 21:35
source share

To solve the library, you can use either paths or path .

From the official document paths :

paths.filep (path)

Gets a boolean value indicating whether the path refers to an existing file.

paths.dirp (path)

Gets a boolean value indicating whether the path refers to an existing directory.

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

If you prefer path rather than paths , you can use path.exists() with assert() to check for the existence of the path while getting its value. Useful when you build a 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 goals are well understood from their names.

0
Apr 04 '19 at 8:04 on
source share

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 end if exist("myfile") then print("hi, file exists") else print("bye, file does not exist") end 
0
Aug 19 '19 at 8:47
source share
 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. :)

-6
Feb 14 '11 at 12:13
source share



All Articles