Exemple de comment vérifier si un fichier existe en python
Table des matières
En utilisant la fonction isfile()
Pour verifier si le fichier (intitulé par exemple "photo_001.png") existe, une solution en python est d'utiliser la fonction isfile comme ceci:
>>> import os>>> os.path.isfile('photo_001.png')
qui retourne un booléen (True ou False) si le fichier 'photo_001.png' existe ou pas.
Si on veut tester si le fichier est disponible sous /users/john/photo_001.png, on peut faire comme ceci:
>>> import os>>> os.path.isdir('/users/john/photo_001.png')
Fonction os.path.exists()
Note 1: attention la fonction os.path.exists() indique si un chemin ("path") existe, mais il peut s'agir aussi bien d'un dossier ou d'un fichier.
>>> import os>>> os.path.exists('/users/john/images)True>>> os.path.isdir('/users/john/images')True>>> os.path.isfile('/users/john/images')False
Note 2: pour obtenir une liste des fichiers et dossiers sous le chemin '/users/john/' on peut utiliser os.listdir():
>>> os.path.listdir('/users/john/')
Références
| Liens | Site |
|---|---|
| isfile | docs.python.org |
| isdir | docs.python.org |
| how to check if a file is a directory or regular file in python? [duplicate] | stackoverflow |
| How do I list all files of a directory? | stackoverflow |
| Getting file size in Python? [duplicate] | stackoverflow |
| Vérifier si un fichier est un dossier ou un simple fichier texte avec python | |
| Python Check If File or Directory Exists | |
| Python: Check if a File or Directory Exists |
