Mots clés : pythonfilefile-existspython
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
84
import os.path os.path.exists(file_path)
os.path.isfile(file_path)
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
69
import os if os.path.isfile(filepath): print("File exists")
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")