7 Ways to Check if a File or Folder Exists in Python

Python’s normal library accommodates many of the performance a developer wants to resolve an issue. On this tutorial, you’ll study a number of methods to verify the existence of a file or folder utilizing solely built-in modules.

Checking {that a} file or script is in the fitting place is essential for any CLI program. Your program might grow to be unusable if a selected file shouldn’t be current on the time of execution.

In right this moment’s tutorial, you may study some fast methods to verify if a file or listing exists in Python.

Earlier than beginning

Earlier than operating any of the instructions beneath, be sure you have Python 3 put in in your system. Open your terminal and kind the next command:

python --version
# Python 3.9.5, my outcome

You probably have a 2.x model, you should use the “python3” command. Try our Python set up information if you do not have Python 3 put in.

We’ll be utilizing some check information together with this tutorial, so be sure you create the next information:

contact testfile.txt
mkdir testdirectory/ 
contact testdirectory/otherfile.txt

The above instructions create a file to play with, a check listing, and one other file in it check folder. The information will be empty as a result of we need not learn their content material,

Comment: For those who’re utilizing Home windows, arrange a easy file construction for that file with a graphical file supervisor.

Lastly, we’ll be utilizing Ipython as our interactive Python shell, which provides a pleasant interface to work with. That is only a commodity, so not strictly essential.

pip set up ipython

After doing this, you possibly can entry a gorgeous Python shell simply by typing Python.

Ipython interactive shell with Python 3.9

Now that you simply’re all set, let’s take a look at methods to verify if a listing or file exists in Python.

Attempt, Open and Besides

That is the only possibility. For those who attempt to open a file that does not exist, Python returns a FileNotFoundError.

In [1]: open('im-not-here.txt')
---------------------------------------------------------------------------
FileNotFoundError: [Errno 2] No such file or listing: 'im-not-here.txt'

We will reap the benefits of this and deal with the exception in case the file we’re in search of doesn’t exist.

In [2]: strive:
   ...:     file = open('im-not-here.txt')
   ...:     print(file) # File handler
   ...:     file.shut()
   ...: besides FileNotFoundError:
   ...:     print('Sorry the file we're in search of doesn' exist')
   ...:     exit()
   ...: 
Sorry the file we're in search of would not exist

Within the above code, we print a customized message and cease this system execution if the file doesn’t exist.

Observe how the Exit() operate is executed provided that an exception is thrown. Let’s examine what occurs if the file we’re in search of really exists.

In [2]: strive:
   ...:     file = open('testfile.txt')
   ...:     print(file) # File handler
   ...:     file.shut()
   ...: besides FileNotFoundError:
   ...:     print('Sorry the file we're in search of would not exist')
   ...:     exit()
   ...: 
<_io.TextIOWrapper title='testfile.txt' mode='r' encoding='UTF-8'>

Discover how we shut the file proper after we open it. Based on the Python documentation, it’s thought of good apply.

calling <span class="pre">file.write()</span> with out utilizing the <span class="pre">with</span> key phrase or name <span class="pre">file.shut()</span> energy outcome within the arguments of <span class="pre">file.write()</span> shouldn’t be utterly written to disk, even when this system closes efficiently.

Even when we do not write to the file, it’s extremely beneficial that we shut the file as it could possibly result in a number of efficiency points.

If we do not wish to shut the file ourselves, we are able to use the of context supervisor. It exactly allocates and releases sources, which is why we need not shut the file.

In [3]: strive:
   ...:     with open('testfile.txt') as file:
   ...:         print(file)
   ...:         # No want to shut the file
   ...: besides FileNotFoundError:
   ...:     print('Sorry the file we're in search of would not exist')
   ...:     exit()
   ...: 
   ...: 
<_io.TextIOWrapper title='testfile.txt' mode='r' encoding='UTF-8'>

This methodology is extraordinarily helpful when writing to information, however it’s inefficient if we simply wish to verify if a file exists. Let us take a look at different choices to realize this.

os.path.exists()

The os module gives a number of capabilities for interacting with the working system. To verify if a file or folder exists, we are able to use the path.consists() operate that accepts the trail to the file or listing as an argument. It returns a boolean worth primarily based on the existence of the trail.

Comment: A path is the distinctive location of a file or folder in a file system

In Python, the os.path submodule accommodates capabilities designed completely to work with file paths. All of those capabilities settle for the trail argument as strings or bytes, and you may resolve to work with absolute paths, for instance:

/dwelling/daniel/.bashrc

Or with relative paths, relying on the listing the place you run the script:

.bashrc
# Operating the script in my dwelling folder

Listed below are a number of examples utilizing the os.path.exists() operate, executed within the folder the place my check information are situated:

In [1]: import os

In [2]: os.path.exists('testfile.txt')
Out[2]: True

In [3]: os.path.exists('testdirectory')
Out[3]: True

In [4]: os.path.exists('hey-i-dont-exist')
Out[4]: False

As you possibly can see, it returns WHERE when testing with the testfile.txt file and the check folder folder, and False when the file doesn’t exist.

os.pad.isfile()

For those who simply needed to show the existence of a file (not a listing), you’ll use the os.pad.isfile() operate.

In [1]: import os

In [2]: os.path.isfile('testfile.txt')
Out[2]: True

In [3]: os.path.isfile('testdirectory/')
Out[3]: False

In [4]: os.path.isfile('i-dont-even-exist')
Out[4]: False

In [5]: os.path.isfile('testdirectory/otherfile.txt')
Out[5]: True

Comment: In UNIX, all directories finish with a slash (/), whereas in Home windows we use a backslash ().

Within the code above the isfile() operate return False let’s examine why on two events:

  • testdirectory/ is a listing, due to this fact it isn’t thought of a file. This isn’t totally true, since in Linux all the things is a file descriptor, however Python treats directories otherwise for comfort (when you attempt to open a listing, you get a IsADirectoryError)
  • i-dont-even-exist factors to a file that paradoxically would not exist

os.pad.isdir()

To verify if a folder is in the fitting place, you want to verify the os.pad.isdir() operate, which returns solely WHERE if the desired path factors to a listing.

In [1]: import os

In [2]: os.path.isdir('testfile.txt')
Out[2]: False

In [3]: os.path.isdir('testdirectory')
Out[3]: True

In [4]: os.path.isdir('anotherfile.txt')
Out[4]: False

Discover how the examples above recur False even when the trail factors to an present file.

sphere

The glob module gives capabilities to work with Unix shell-like patterns (that is why it would not work nicely on Home windows). To verify whether or not a file matches a sample within the present listing, you should utilize the glob.glob() operate.

In [1]: import glob

In [2]: glob.glob('testfile.txt')
Out[2]: ['testfile.txt']

In [3]: glob.glob('testdirectory')
Out[3]: ['testdirectory']

Within the code above, the sample handed to the glob operate is a traditional string representing the trail to the check file and listing. Since each paths exist, the operate returns a listing of the matching path names in them.

Comment: If the sample did not match, you bought an empty checklist.

Since we are able to move patterns to the glob operate, why not check a few of its predominant advantages?

The code beneath retrieves all file paths with an extension .textual content And .py respectively:

In [4]: glob.glob('*.txt')
Out[4]: ['testfile.txt']

In [5]: glob.glob('*.py')
Out[5]: 
['pathlib-exists.py',
 'list-dir.py',
 'glob-file.py',
 'open-except.py',
 'subprocess-test.py',
 'isfile.py',
 'exists.py',
 'isdir.py']

Utilizing the trail class

The Path class is among the finest methods to work with paths as a result of it provides us a clear interface to work with file paths as objects.

The icing on the cake is that Path situations have all of the strategies you want to get details about a given path. This consists of related functionalities because the earlier choices.

Comment: You want Python 3.4 or larger to make use of the pathlib library

The Path strategies you’ll use:

  • Path().exists()
  • path().is_file()
  • Path().is_dir()

Test if a path exists

In [1]: from pathlib import Path

In [2]: Path('testfile.txt').exists()
Out[2]: True

In [3]: Path('im-not-here.txt').exists()
Out[3]: False

In [4]: Path('testdirectory').exists()
Out[4]: True

Works the identical as os.path.exists().

Test if the trail factors to a file

In [5]: Path('testfile.txt').is_file()
Out[5]: True

In [6]: Path('testdirectory').is_file()
Out[6]: False

Equal to os.pad.isfile().

Test if the trail factors to a folder

In [7]: Path('testfile.txt').is_dir()
Out[7]: False

In [8]: Path('testdirectory').is_dir()
Out[8]: True

Corresponds to os.pad.isdir().

subprocess

In case you are a fan of sub-process modules, it’s best to find out about this selection. You possibly can decide whether or not a file or listing exists through the use of the check command.

Comment: The check command solely works in Unix.

The next check flags will get the job achieved:

  • heads: Test if a path exists
  • check -f: Test if a file exists
  • d key: Test if a folder exists

If you wish to dive into extra check flags, you possibly can learn the information by operating:

man check

Test subprocess path:

The code beneath determines if a path exists by evaluating the subprocess’s return code to 0.

Bear in mind in linux if a course of went nicely it’s going to return null, if not it’s going to return another code.

In [1]: from subprocess import run

In [2]: run(['test', '-e', 'testfile.txt']).returncode == 0
Out[2]: True

In [3]: run(['test', '-e', 'im-not-here.txt']).returncode == 0
Out[3]: False

Within the first assertion, we import the subprocess module, then use the run operate and retrieve the return code.

Confirm the existence of a subprocess file

In [4]: run(['test', '-f', 'testfile.txt']).returncode == 0
Out[4]: True

In [5]: run(['test', '-f', 'testdirectory']).returncode == 0
Out[5]: False

To verify a subprocess listing:

In [6]: run(['test', '-d', 'testfile.txt']).returncode == 0
Out[6]: False

In [7]: run(['test', '-d', 'testdirectory']).returncode == 0
Out[7]: True

It’s not beneficial to make use of this selection because it consumes extra sources and we do not get any profit from it.

To sum up

Python is among the most generally used programming languages ​​to automate processes by interacting with the working system. One cool factor you are able to do with it’s verify if a file or folder exists.

The best to do that are:

  • Open and deal with file exceptions instantly
  • The habits consists() operate of the os.pad or padlib modules.

On this tutorial you realized:

  • Easy methods to open a file and deal with exceptions in case it would not exist
  • The that means of paths
  • 3 completely different capabilities the os.pad submodule gives the flexibility to verify the existence of a file or listing
  • Unix makes use of slashes (/), whereas Home windows makes use of slashes ().

Learn extra: What’s a subprocess in Python? [5 Usage Examples]

Leave a Comment

porno izle altyazılı porno porno