How to check if a file exists using Python

10

How to check if a file exists, in Python, without using a block try: ?

    
asked by anonymous 29.01.2014 / 18:37

3 answers

12

You can do:

import os.path
os.path.isfile('nome do arquivo')

But this approach is not considered the most pythonic. Following the principle that it is better to ask for forgiveness than permission, it is better to do:

try:
   with open('nome_do_arquivo', 'r') as f:
       processar_arquivo(f)
except IOError:
    print u'Arquivo não encontrado!'

os.path.isfile() and os.path.exists() only report that the file or directory existed at the time that line of code was running. In the (tiny) length of time between running this line and executing the code that depends on that check, it is possible that the file may have been created or deleted.

This type of situation is a race condition , which can cause security vulnerabilities. A possible attack would be to create a symlink to any file immediately after the program checks whether the file exists or not. This way, a file could be read or overwritten using the same level of access and privileges that your program has.

    
29.01.2014 / 19:26
5

Try this:

import os.path
print os.path.isfile(fname)

There is the method os.path.exists() also, but note that it returns true for directories.

    
29.01.2014 / 18:42
3

You can use exists :

import os.path
os.path.exists('nome.ext')

But that will also return True to directories, if you want to make sure it's a file actually use isfile :

import os.path
os.path.isfile('nome.ext')
    
29.01.2014 / 18:43