Python - Comment vérifier si un fichier existe
En Python, nous pouvons utiliseros.path.isfile()
oupathlib.Path.is_file()
(Python 3.4) pour vérifier si un fichier existe.
1. pathlib
Nouveau dans Python 3.4
from pathlib import Path fname = Path("c:\\test\\abc.txt") print(fname.exists()) # true print(fname.is_file()) # true print(fname.is_dir()) # false dir = Path("c:\\test\\") print(dir.exists()) # true print(dir.is_file()) # false print(dir.is_dir()) # true
Si cochez
from pathlib import Path fname = Path("c:\\test\\abc.txt") if fname.is_file(): print("file exist!") else: print("no such file!")
2. os.path
Un exemple classique deos.path
.
import os.path fname = "c:\\test\\abc.txt" print(os.path.exists(fname)) # true print(os.path.isfile(fname)) # true print(os.path.isdir(fname)) # false dir = "c:\\test\\" print(os.path.exists(dir)) # true print(os.path.isfile(dir)) # false print(os.path.isdir(dir)) # true
Si cochez.
import os.path fname = "c:\\test\\abc.txt" if os.path.isfile(fname): print("file exist!") else: print("no such file!")
3. Essayez: Sauf
Nous pouvons également utiliser lestry except
pour vérifier si un fichier existe.
fname = "c:\\test\\no-such-file.txt" try: with open(fname) as file: for line in file: print(line, end='') except IOError as e: print(e)
Sortie
[Errno 2] No such file or directory: 'c:\\test\\no-such-file.txt'