How to Check whether a File Exists in Python
Created
Modified
Using os.path.exists Method
Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists. See the following example:
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import os
if os.path.exists("file.txt"):
print("File exists")
# --- Source Code ---
# def exists(path):
# """Test whether a path exists. Returns False for broken symbolic links"""
# try:
# os.stat(path)
# except (OSError, ValueError):
# return False
# return True
File exists
This returns True for both files and directories.
Using os.path.isfile Method
Return True if path is an existing regular file. For example,
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import os
# os.path.isdir
if not os.path.isfile("f.txt"):
print("File does not exist")
File does not exist
Using pathlib Module
Starting with Python 3.4, the pathlib module offers an object-oriented approach, try this:
#!/usr/bin/python3
# -*- coding: utf8 -*-
# Import module
import pathlib
f = pathlib.Path("file.txt")
# f.is_dir() f.exists()
if f.is_file():
print("File exists")
File exists