14 C
Jaipur
Sunday, November 29, 2020

Check If File Exists in Python – Linux Hint

Must read

Gaming laptop deal: save $390 on the Dell G5 15 in the early Cyber Monday sale

We've just spotted a fantastic gaming laptop deal over on the official Dell website for anyone looking for a solid first step into the...

Where to buy Oculus Quest 2 on Cyber Monday – and why are there no deals?

Looking for Oculus Quest 2 Cyber Monday deals? Unfortunately, we haven't really seen any across the Black Friday weekend. In fact, the VR headset...

See how iPhone XR deals came down to only £20 a month this Black Friday weekend

If you're in the market for a fairly priced iPhone, it's likely you'll have considered some iPhone XR deals before. While it's not quite...

Xbox Series X controllers are at their best price yet for Cyber Monday

If you're after a good Xbox Series X Cyber Monday deal, these Xbox Series X controllers should do just the trick. You'll find a...

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.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article

Gaming laptop deal: save $390 on the Dell G5 15 in the early Cyber Monday sale

We've just spotted a fantastic gaming laptop deal over on the official Dell website for anyone looking for a solid first step into the...

Where to buy Oculus Quest 2 on Cyber Monday – and why are there no deals?

Looking for Oculus Quest 2 Cyber Monday deals? Unfortunately, we haven't really seen any across the Black Friday weekend. In fact, the VR headset...

See how iPhone XR deals came down to only £20 a month this Black Friday weekend

If you're in the market for a fairly priced iPhone, it's likely you'll have considered some iPhone XR deals before. While it's not quite...

Xbox Series X controllers are at their best price yet for Cyber Monday

If you're after a good Xbox Series X Cyber Monday deal, these Xbox Series X controllers should do just the trick. You'll find a...

Incredible Cyber Monday deal: save £1,877 on this 55-inch Alienware gaming OLED monitor

Dell has stolen the limelight this sales season with the Alienware 55-inch AW5520QF getting a major £1,877 price cut – and this stellar early...