python - Comment vérifier si un fichier existe sans exception

Mots clés : pythonfilefile-existspython

meilleur 5 Réponses python - Comment vérifier si un fichier existe sans exception

vote vote

96

import os.path os.path.isfile(fname)  
from pathlib import Path  my_file = Path("/path/to/file") if my_file.is_file():     # file exists 
if my_file.is_dir():     # directory exists 
if my_file.exists():     # path exists 
try:     my_abs_path = my_file.resolve(strict=True) except FileNotFoundError:     # doesn't exist else:     # exists 
vote vote

84

import os.path os.path.exists(file_path) 
os.path.isfile(file_path) 
vote vote

80

>>> os.path.isfile("/etc/password.txt") True >>> os.path.isfile("/etc") False >>> os.path.isfile("/does/not/exist") False >>> os.path.exists("/etc/password.txt") True >>> os.path.exists("/etc") True >>> os.path.exists("/does/not/exist") False 
vote vote

69

import os  if os.path.isfile(filepath):    print("File exists") 
vote vote

55

import os  PATH = './file.txt' if os.path.isfile(PATH) and os.access(PATH, os.R_OK):     print("File exists and is readable") else:     print("Either the file is missing or not readable") 

Questions similaires