Advertisement
Advertisement


How do I check whether a file exists without exceptions?


Question

How do I check if a file exists or not, without using the try statement?

2020/05/04
1
5741
5/4/2020 7:28:02 PM


You have the os.path.exists function:

import os.path
os.path.exists(file_path)

This returns True for both files and directories but you can instead use

os.path.isfile(file_path)

to test if it's a file specifically. It follows symlinks.

2018/10/19

Unlike isfile(), exists() will return True for directories. So depending on if you want only plain files or also directories, you'll use isfile() or exists(). Here is some simple REPL output:

>>> 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
2020/03/03

import os.path

if os.path.isfile(filepath):
2017/06/21

Use os.path.isfile() with os.access():

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")
2020/03/26

import os
os.path.exists(path) # Returns whether the path (directory or file) exists or not
os.path.isfile(path) # Returns whether the file exists or not
2018/06/02

Source: https://stackoverflow.com/questions/82831
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]