Piton

Check If File Exists in Python

Check If File Exists in Python

Python provides a built-in operating system (OS) module that can be used to access OS files and directories. Any computer user often finds the need to check whether a file exists in a system. For example, suppose you are working on a file system and want to make sure that a file is available before performing any major operations on it. If you attempt to navigate or open a non-existent file, then this would cause an error. This article shows you how to use various Python file-checking mechanisms.

There are three different Python functions that can be used to verify the existence of a file:

  1. path.exists()
  2. path.isfile()
  3. exists()

The following sections discuss these functions in greater detail.

1. os.path.exists()

The path.exist() function is a built-in function provided by the os module. This function takes the path file and returns 'true' if the file is present. If the file is not present, then the function returns 'false.' Before using path.exist(), first, you must import the os module.

Let us an example of this.

#importing os module
import os.path
# using os.path.exist() to check the existence of file
# specifying the path of the file
print(os.path.exists("/home/linuxhint/Documents/test.txt"))

Output
In this output, you can see that the os.path.exists() function returns 'true,' which means that the file is present in the specified path.

The file is also present in the directory.

Let us now modify the program given above. We will change the print statement to make the result more clear.

#importing os module
import os.path
# using os.path.exist() to check the existence of a file
# specifying the path of the file
print("The file exist: ",os.path.exists("/home/linuxhint/Documents/test.txt"))

Output

Next, we will change the file and specify a file that does not exist, instead. You will observe that the os.path.exists() function will return 'false.'

#imprting os module
import os.path
# using os.path.exist() to check the existence of file
# specifying the path of the file
print("The file exist: ",os.path.exists("/home/linuxhint/Documents/abcfile.txt"))

Output
This output shows that the os.path.exists() function returns 'false' when the file does not exist.

2. os.path.isfile()

The os.path.isfile() function is also used to check the existence of a file. This is the most common way of checking the existence of a file. The os.path.isfile() function takes the path of a file as a parameter and checks whether the given path contains a valid file. This function returns 'true' when the given path is a regular file and returns 'false' if the given path is not a regular file. Let's see an example of this.

#imoprting os module
import os.path
# using os.path.isfile() to check the existence of file
# specifying the path of the file
print("This is a file: ",os.path.isfile("/home/linuxhint/Documents/test.txt"))

Output
The os.path.isfile() function returns 'true.'

In this example, we will specify the name of the invalid file in the given path. In the output, you will see that the os.path.isfile() function returns 'false.'

#importing os module
import os.path
# using os.path.isfile() to check the existence of file
# specifying the path of the file
print("This is a file: ",os.path.isfile("/home/linuxhint/Documents/fileTest.txt"))

Output

3. pathlibPath.exists()

The Python 3.4 and above version(s) have the pathlib module to deal with file systems and paths.

Let us see an example of this function:

#importing pathlib module
import pathlib
#storing the file path in a variable using the Path() function
filePath=pathlib.Path("/home/linuxhint/Documents/test.txt")
#using exists() function to check whether the file exists
if filePath.exists():
print("The file exists")
else:
print("The file does not exist")

Output
The given file exists in the directory; therefore, the exists() function returns 'true.'

Next, we will specify the invalid file path in the Path() function and check the output.

#importing pathlib module
import pathlib
#storing the file path in a variable using the Path() function
filePath=pathlib.Path("/home/linuxhint/Documents/testabc.txt")
#using exists() function to check whether the file exists
if filePath.exists():
print("The file exists")
else:
print("The file does not exist")

Output
The exists() function returns 'false' and the else statement is executed because the file does not exist in the given directory.

Similarly, we can verify the existence of a directory in Python using the following built-in functions:

os.path.isdir()

The os.path.isdir() function returns 'true' if the specified directory exists, and the function returns 'false' if the directory does not exist.

Let us see an example of this:

#importing os module
import os.path
# using os.path.isdir() to check the existence of directory
# specifying the path of the documents directory
print("This is a directory: ",os.path.isdir("/home/linuxhint/Documents"))

Output
The os.path.isdir() function returns true because the directory exist in the system.

Now let's specify the path of invalid directory.

#importing os module
import os.path
# using os.path.isdir() to check the existence of direcoty
# specifying the path of the MyDocuments directory
print("This is a directory: ",os.path.isdir("/home/linuxhint/MyDocuments"))

Output

Conclusion

In this article, we have explained file existence verification methods in Python through several examples. This article showed various ways of verifying the existence of a file in Python. The os and pathlib modules provide built-in functions to verify the existence of any file in a system. This knowledge will prove useful, as it will often be the case in Python and programming that you require verification of a file's existence.

How to change Left & Right mouse buttons on Windows 10 PC
It's quite a norm that all computer mouse devices are ergonomically designed for right-handed users. But there are mouse devices available which are s...
Emulate Mouse clicks by hovering using Clickless Mouse in Windows 10
Using a mouse or keyboard in the wrong posture of excessive usage can result in a lot of health issues, including strain, carpal tunnel syndrome, and ...
Add Mouse gestures to Windows 10 using these free tools
In recent years computers and operating systems have greatly evolved. There was a time when users had to use commands to navigate through file manager...