Check if a File or Directory Exists
Check whether a file exists using PythonWhen writing Python scripts , we might just need to know if a specific file or directory or a path exists or not . Python offers several alternative ways of checking whether a file exists or not. To check this, we use functions built into the core language and the Python standard library . They are:
- pathlibPath.exists() (Python 3.4+)
- open() and try...except
os.path.isfile()This is the simplest way to check if a file exists or not.
import os.path filename = "my_file.txt" if(os.path.isfile(/filepath/filename)): print("File Exists!!") else: print("File does not exists!!")If the file "my_file.txt" exist in the current path, it will return true else false .
os.path.exists()Python os.path.exists() method is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not in the specified path . 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.
Check file or directory/folder exists using Python os.path.exists() method
import os dirname = "temp" filename = "my_file" #check directory exists if(os.path.exists(dirname)): print("Directory Exists") else: print("Directory does not exists") #check file exists if(os.path.exists(filename)): print("File Exists") else: print("File does not exists")
pathlibPath.exists() (Python 3.4+)Traditionally, Python has represented file paths using regular text strings. Python 3.4 and above versions have pathlib Module for handling with file system path. This module offers classes representing filesystem paths with semantics appropriate for different OS. It gathers the necessary functionality in one place and makes it available through methods and properties on an easy-to-use Path object. Also, it used object-oriented approach to check if file exist or not.
import pathlib filename = "my_file.txt" file = pathlib.Path(/filepath/filename) if file.exists (): print("file does exist at the moment!!") else: print("no such file exists at the moment!!")If the file "my_file.txt" exist in the current path, it will return true else false .
PureWindowsPathIn Python pathlib module , path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations. When you use pathlib module , Pure paths are useful in some special cases. For example, if you want to manipulate Windows paths on a Unix machine (or vice versa), you cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath .
open() and try...exceptIt is important to note that checking for existence and then opening a file is always open to race-conditions . Just because the file existed when you checked doesn't guarantee that it will be there when you need to open it. Race conditions happen when you have more than one process accessing the same file . Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it. Thus there might still be an exception being thrown, even though your code is "certain" that the file exists. So, it's safer to use a try...except around the attempt to open it.
try: myFile = open("d:/test.txt") # Do something operations with the file except IOError: print("no such file exists!!") finally: myFile.close()If file is there on the path, we can use the file. Otherwise, the open command will throw an error that we catch in the except block. It is recommended to use the "with" keyword , which makes sure the file is properly closed after the file operations are completed. The "with statement" creates an execution block and object created in the with statement will be destroyed or closed when this execution block ends.
try: with open("d:/test.txt") as myFile: print("file exists!!") # Do something operations with the file except IOError: print("no such file exists!!")In the examples above, we were using the Python exception handling and opening the file to avoid the race condition.
Check whether a directory/Folder exists using PythonPython os.path.isdir() method used to check whether the specified path is an existing directory or not.
How to get list of files in directory and sub directoriesPython os.listdir() method in python is used to get the list of all files and directories in the specified directory.
PermissionThe os.access() method verifies the access permission specified in the mode argument.
os.access(path, mode)Return True if access is allowed, False if not. When using access() method to check if a user is authorized to open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it.
import os import os.path filePath='./myfile.txt' if os.path.isfile(filePath) and os.access(filePath, os.R_OK): print("File exists and is readable") else: print("File is missing or not readable")
- os.F_OK: Tests existence of the path.
- os.R_OK: Tests readability of the path.
- os.W_OK: Tests writability of the path.
- os.X_OK: Checks if path can be executed.
- How to open and close a file in Python
- How to write files in python
- How to read a file properly in Python
- How to read a file line by line in Python
- How to use Split in Python
- Directory Operations Using Python
- File Access Mode in Python
- Difference between read, readline and readlines | python
- Python file positions | seek() and tell()
- How to Copy a File using Python