How do I check whether a file exists using Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

https://docs.python.org/3.6/reference/compound_stmts.html#try https://docs.python.org/3.6/reference/compound_stmts.html#try

Answers

https://docs.python.org/2/library/os.path.html#os.path.isfile https://docs.python.org/2/library/os.path.html#os.path.isfile

https://docs.python.org/2/library/os.path.html#os.path.isfile https://docs.python.org/2/library/os.path.html#os.path.isfile
import os.path
os.path.isfile(fname) 

if you need to be sure it s a file.

https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-using-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils