How to check if a file exists using Python

Asked

Viewed 15,049 times

13

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

3 answers

16


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 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 that the file or directory existed at the time that line of code was being executed. In the (lowercase) time span between running this line and executing the code that depends on this check, it is possible that the file may have been created or deleted.

That kind of situation is a race condition, that 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 access level and privileges as your program has.

  • using Try, except is the best way even :)

6

Try it like this:

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

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

6

You can use exists:

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

But it will also return True for directories, if you want to make sure it’s a really use file isfile:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.