Originally posted on maekuseof.
Here are multiple ways to check for a specific file or directory using Python.
Python’s dependency on external files is a crucial aspect, it’s wise to pay heed to the base/source files before executing any code. Before running a particular program, you need to ensure your source files exist at the specified location.
Every developer understands the need to create fall back codes, which can save a prorgram from failing in the case that a condition isn’t met. In Python, there are several ways to check if a file exists; here are the top methods you should know about.
1. Try and Except Statements
The try and except statement checks a command and produces an output. In the code below, the try statement will attempt to open a file (testfile.txt). If Python’s processor is able to locate the file, it will open the file and print the result File is open and available for use.
try: f = open('testfile.txt') print("File is available for use") f.close() except IOError: print('File is not accessible')
If it encounters an error, it will print the result File is not accessible. Once the full code is compiled and executed, it will close the open file if it was opened.
Python’s dependency on external files is a crucial aspect, and you need to pay heed to the base/source files, before executing any codes.
Before executing a particular program, ensure your source files exist at the specific location.
Python has a built-in module OS which can be called upon to interact with the underlying files, folders and directories. Python’s os.path.isfile() method can be used to check a directory and if a specific file exists.
The first step is to import the built-in function using the import os.path library. The next command checks if the file exists on the specific location.
import os.path os.path.isfile(r"C:\Users\Wini Bhalla\Desktop\Python test file.txt")
The output returns True, as the file exists at the specific location. If the file does not exist, Python will return False.
On similar grounds, the import os library statement can be used to check if the directory exists on your system.
The syntax is rather simple:
Import os.path os.path.exists(r"C:\Users\Wini Bhalla\Desktop\test")
Just like the previous step, if the directory/folder is found on the specified system path, Python returns True, and subsequently, False, if the directory/folder isn’t found.
Just like os.path.isfile and os.path.exists(), os.path.isdir() is a sub-function of the os library. The only difference here is that this command only works for directories. As expected, the use of this syntax returns a boolean value based on the existence of directories.
import os os.path.isdir(r"C:\Users\Wini Bhalla\Desktop\OS")
The output is True, since the folder/directory exists at the specified path.
import os os.path.isdir(r"C:\Users\Wini Bhalla\Desktop\testdirectory")
The output is False, since the folder/directory doesn’t exist at the specified path.
Python 3.4 and above versions offer the Pathlib module, which can be imported using the import function. Pathlib captures the necessary functionalities in one place, and makes it available through various methods to use with the path object.
To Use Pathlib:
import pathlib file = pathlib.Path(r"C:\Users\Wini Bhalla\Desktop\Python test file.txt") if file.exists (): print ("File exists") else: print ("File does not exist")
As per the existence of the file, the output will display whether or not the file exists in the specified path. Ideally, the code in the print statement can be changed, as per the requirements of your program
The listdir method in Python returns a list of the all files in a specific directory, as specified by the user. However, this method will not return any files existing in subfolders.
The listdir method only accepts one parameter, the file path. Ideally, the file path will be file and folder names you’d like to retrieve.
The basic syntax includes:
In the example below, you can create a loop to go through all the files listed in the directory and then check for the existence of the specified file declared with the if statement.
import os path = r'C:\Users\Wini Bhalla\Desktop' files = os.listdir(path) print (files)
This code will print out the list of files available in the current directory.
import os path = r'C:\Users\Wini Bhalla\Desktop' files = os.listdir(path) for f in files: if f == "test.txt": print("File exists") else: print("File does not exist")
Further on, when the loop is run, the listdir function along with the if statement logic will cycle through the list of files and print out the results, depending on the conditions passed within the print statement.
7. Glob Module
The glob module matches all the pathnames with the specified parameters and succinctly allows you to access the file system. Since glob is used for pattern matching, you can use it to check a file’s status.
There are two references of the path:
- Absolute path: Use this when you want to look for a file in a different directory.
- Relative path: Use this when you want to look for a file in the current directory.
If the file is found, the code will return True, otherwise it’ll return False.
An example of Glob’s usage:
import glob if glob.glob(r"C:\Users\Wini Bhalla\Desktop\test.txt"): print ("File exist") else: print("File does not exist")
The output from this code will print the result, if the file is found.
The test command in the sub-process module is an efficient way of testing the existence of files and directories. The test commands only work in Unix based machines and not Windows based OS machines.
You can use the following commands as per your needs:
- test -e: Check the existence of a path
- test -f: Check the existence of a file
- test-d: Check the existence of a folder
Verifying a Path With Sub-process:
from subprocess import run run(['test', '-e', 'testfile.txt']).returncode == 0 run(['test', '-e', 'im-not-here.txt']).returncode == 0
This code called the test function followed by ‘-e’ to verify the existence of a path. The function shows False for an invalid path.
Verifying a File With Subprocess:
run(['test', '-f', 'testfile.txt']).returncode == 0 run(['test', '-f', 'testdirectory']).returncode == 0
The ‘-f’ function tests the existence of a file and returns False for a directory.
Verifying a Directory With Subprocess:
run(['test', '-d', 'testfile.txt']).returncode == 0 run(['test', '-d', 'testdirectory']).returncode == 0
The ‘-d’ function tests the existence of a directory and returns False for any file query in the test command.
Which Command Will You Use to Locate Your Files?
Python is a relatively easy-to-use language, and it offers a lot of options to the end users. For checking the existence of a file(s), you can use any of the procedures listed above.
However, if you’re a beginner, there are always ways to learn Python. Since Python is a vast language, it’s best to spend some time understanding the different nuances and its range of commands.