¿Cómo puedo verificar si un archivo existe, usando Python, sin necesidad de utilizar un try:
afirmación?
Respuestas
¿Demasiados anuncios?
rslite
Puntos
17279
PierreBdR
Puntos
11479
bortzmeyer
Puntos
12246
A diferencia de isfile()
, exists()
dará lugar a Verdadero para los directorios.
Por lo tanto, dependiendo de si quieres sólo archivos o también directorios, utilizarás isfile()
o exists()
.
>>> print os.path.isfile("/etc/passwd")
True
>>> print os.path.isfile("/etc")
False
>>> print os.path.isfile("/does/not/exist")
False
>>> print os.path.exists("/etc/passwd")
True
>>> print os.path.exists("/etc")
True
>>> print os.path.exists("/does/not/exist")
False
Yugal Jindle
Puntos
5931
Utilice os.path.isfile()
con os.access()
:
import os
import os.path
PATH='./file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print "File exists and is readable"
else:
print "Either file is missing or is not readable"
benefactual
Puntos
2373