How do I check whether a file exists or not, without using the try statement?
- 15Note: your program will not be 100% robust if it cannot handle the case where a file already exists or doesn't exist at the time you actually try to open or create it respectively. The filesystem is concurrently accessible to multiple programs, so the existance-check you did prior to these actions might already be outdated by the time your program acts on it.masterxilo– masterxilo2023-11-18 17:00:49 +00:00Commented Nov 18, 2023 at 17:00
- 2@KaiLando Not realistically. It would require you to check if the file exists every time you read/write to it, and even then there is the edge case that it disappears between the if and the access.Ted Klein Bergman– Ted Klein Bergman2024-02-14 13:39:19 +00:00Commented Feb 14, 2024 at 13:39
- 3@KaiLando It's not enough. If it exists it might no longer exist after the check is completed.Ted Klein Bergman– Ted Klein Bergman2024-02-15 08:38:45 +00:00Commented Feb 15, 2024 at 8:38
- Note that you do not write to something with a filename. You write to a filedescriptor. Which will map to an inode. The directory entry that names that inode could be removed while you have the file open. So you indeed do not need to test on every write if the filename still exists, but you could be writing to a filesystem location that is going to be unreachable after you release the filedescriptorde2Zotjes– de2Zotjes2025-02-17 19:04:03 +00:00Commented Feb 17 at 19:04
41 Answers
exists() and is_file() methods of 'Path' object can be used for checking if a given path exists and is a file.
Python 3 program to check if a file exists:
# File name: check-if-file-exists.py from pathlib import Path filePath = Path(input("Enter path of the file to be found: ")) if filePath.exists() and filePath.is_file(): print("Success: File exists") else: print("Error: File does not exist") Output:
$ python3 check-if-file-exists.py
Enter path of the file to be found: /Users/macuser1/stack-overflow/index.html
Success: File exists
$ python3 check-if-file-exists.py
Enter path of the file to be found: hghjg jghj
Error: File does not exist
Comments
import os.path def isReadableFile(file_path, file_name): full_path = file_path + "/" + file_name try: if not os.path.exists(file_path): print "File path is invalid." return False elif not os.path.isfile(full_path): print "File does not exist." return False elif not os.access(full_path, os.R_OK): print "File cannot be read." return False else: print "File can be read." return True except IOError as ex: print "I/O error({0}): {1}".format(ex.errno, ex.strerror) except Error as ex: print "Error({0}): {1}".format(ex.errno, ex.strerror) return False #------------------------------------------------------ path = "/usr/khaled/documents/puzzles" fileName = "puzzle_1.txt" isReadableFile(path, fileName) 1 Comment
isReadableFile(path,fileName) will return True if the file is reachable and readable by the process\program\threadUse os.path.exists() to check whether file exists or not:
def fileAtLocation(filename,path): return os.path.exists(path + filename) filename="dummy.txt" path = "/home/ie/SachinSaga/scripts/subscription_unit_reader_file/" if fileAtLocation(filename,path): print('file found at location..') else: print('file not found at location..') 4 Comments
import os path = "/path/to/dir" root, dirs, files = os.walk(path).next() if myfile in files: print("yes it exists") This is helpful when checking for several files, or if you want to do a set intersection/ subtraction with an existing list of files.
2 Comments
os.walk find all files under a directory tree -- if the user wants to check for ./FILE, it's unlikely he'd want to treat ./some/sub/folder/FILE as a match, which your solution does; and (2) your solution is very inefficient compared to a simple os.path.isfile() call in the case where there are many files below the current directory. In the case where no matching filename-without-path exists within the tree, your code will enumerate every single file in the tree before returning false.os.walk produces a generator; iterating over that generator would find all the files in the directory tree, but this code simply uses a single next call in order to investigate the top level of the tree. This can, of course, be done more simply with os.listdir, which in turn is — yes — too much work when the exact path can be tested directly with os.path.isfile.To check if a file exists,
from sys import argv from os.path import exists script, filename = argv target = open(filename) print "file exists: %r" % exists(filename) 1 Comment
Code:
import os check_if_path_exists=lambda path:os.path.exists(path) or:
import os def check_if_path_exists(path): return os.path.exists(path) This code checks whether the file or path specified by the argument path exists using the os.path.exists() function. It checks if the path exists and returns True if it exists and False if it doesn't exist. Example:
check_if_path_exists("C:/") #True check_if_file_exists("ofhiafdajfihguihfa:/") #False Comments
You can use os.listdir to check if a file is in a certain directory.
import os if 'file.ext' in os.listdir('dirpath'): #code 1 Comment
Use:
import os # For testing purposes the arguments defaulted to the current folder and file. # returns True if file found def file_exists(FOLDER_PATH='../', FILE_NAME=__file__): return os.path.isdir(FOLDER_PATH) \ and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME)) It is basically a folder check, and then a file check with the proper directory separator using os.path.join.
Comments
You can use the following open method to check if a file exists + readable:
file = open(inputFile, 'r') file.close() 2 Comments
Another possible option is to check whether the filename is in the directory using os.listdir():
import os if 'foo.txt' in os.listdir(): # Do things This will return true if it is and false if not.
1 Comment
if Path('foo.txt') in Path().iterdir().This is how I found a list of files (in these images) in one folder and searched it in a folder (with subfolders):
# This script concatenates JavaScript files into a unified JavaScript file to reduce server round-trips import os import string import math import ntpath import sys #import pyodbc import gzip import shutil import hashlib # BUF_SIZE is totally arbitrary, change for your app! BUF_SIZE = 65536 # Let’s read stuff in 64 kilobyte chunks # Iterate over all JavaScript files in the folder and combine them filenames = [] shortfilenames = [] imgfilenames = [] imgshortfilenames = [] # Get a unified path so we can stop dancing with user paths. # Determine where files are on this machine (%TEMP% directory and application installation directory) if '.exe' in sys.argv[0]: # if getattr(sys, 'frozen', False): RootPath = os.path.abspath(os.path.join(__file__, "..\\")) elif __file__: RootPath = os.path.abspath(os.path.join(__file__, "..\\")) print ("\n storage of image files RootPath: %s\n" %RootPath) FolderPath = "D:\\TFS-FARM1\\StoneSoup_STS\\SDLC\\Build\\Code\\StoneSoup_Refactor\\StoneSoupUI\\Images" print ("\n storage of image files in folder to search: %s\n" %FolderPath) for root, directories, filenames2 in os.walk(FolderPath): for filename in filenames2: fullname = os.path.join(root, filename) filenames.append(fullname) shortfilenames.append(filename) for i, fname in enumerate(shortfilenames): print("%s - %s" % (i+1, fname)) for root, directories, filenames2 in os.walk(RootPath): for filename in filenames2: fullname = os.path.join(root, filename) imgfilenames.append(fullname) imgshortfilenames.append(filename) for i, fname in enumerate(imgshortfilenames): print("%s - %s" % (i+1, fname)) for i, fname in enumerate(imgshortfilenames): if fname in shortfilenames: print("%s - %s exists" % (i+1, fname)) else: print("%s - %s ABSENT" % (i+1, fname))