13
How to check if a file exists, in Python, without using a block try:
?
13
How to check if a file exists, in Python, without using a block try:
?
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.
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.
Browser other questions tagged python filing-cabinet
You are not signed in. Login or sign up in order to post.
using Try, except is the best way even :)
– Ellison Leão