How to check if a file exists, in Python, without using a block try:
?
How to check if a file exists, in Python, without using a block try:
?
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.
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.