How to check if a file exists in Python - Definitive Guide? -Stack Vidhya (2023)

When working with Python, you may only need to perform certain actions when a file or directory exists.

You can check if a file exists using the file.exists() method in Python.

In this tutorial, you will learn about the different methods available to check if a file exists in Python.

if you are in a hurry

You can use the following code snippet to do thischeck whether the file exists without exception.

  • If the file exists and is readable, then you will see theThe file existsMessage.
  • If the file does not exist or cannot be read, you will see theThe file does not existMessage.
import pathlibfile = pathlib.Path("C:/temp/Test_Folder/test.txt")if file.exists(): print ("El archivo existe")else: print ("El archivo existe")

The file exists, so you see the following output.

Production

The file exists

If you want to understand the details, read on...

You will learn about the different methods available to check if a file exists in Python.

There are three libraries available in Python to check if a file exists.

  • Using the operating system module
  • With pathlib
  • use balloon

Table of contents

Use the OS module to check if the file exists

You can check if a file exists by using theexists()method available in theos.rutaModule. Ask themexist() doc.

Isexists()The method accepts the file path parameter, which must be checked for its existence.

Where from,

  • absolute path– If you want to check whether a file exists in another directory.
    Ö
  • filename– If you want to check the file in the current directory.

Returns,

(Video) #AI & #ML Lecture 8: Feature Selection & Normalization, Data Pre-Processing, TF-IDF, Text Processing

  • RIGHT– If the file exists and is readable
  • NOT CORRECT– If the file does not existÖunreadable The following example shows how to check whether the filetexto.txtconsists in thec:/temp/test_folder/.

Rest

desde os import pathpath.exists("C:/temp/Test_Folder/test.txt")

Since the file exists in the directory, you see the outputRIGHT

Production

RIGHT

So you can check if a file exists by using theoperating system.routeModule.

Use pathlib to check if the file exists

Pathibwill be introduced in Python 3.4. It is the most intuitive library for interacting with the file system. You can use this method to check whether a file exists without exception.

You can installPathibwith the following snippet.

Installation

pip install pathlib

you can use the...Awayclass in thePathibModule to create a route object. Use ofAwayclass you can use theexists()Method to check if the path exists.

CaminoThe class accepts the file path information.

Where from,

  • absolute path– If you want to check whether a file exists in another directory.
    Ö
  • filename– If you want to check the file in the current directory.

Use the following snippet to verify that the file exists by using theRutalibModule.

Rest

import pathlibfile = pathlib.Path("C:/temp/Test_Folder/test.txt")if file.exists(): print ("El archivo existe")else: print ("El archivo existe")

if the file existsjis legible, then theexists()the method returnsRIGHT. Therefore, the if statement is executed.

Production

The file exists

Fragment 2

import pathlibfile = pathlib.Path("C:/temp/Test_Folder/test_1.txt")if file.exists(): print ("El archivo existe") else: print ("El archivo existe")

If the file does not exist or cannot be read, theexists()the method returnsRIGHT. therefore, themorethe statement is executed.

Production

(Video) The DataHour: Everything you need to know about Speech Recognition

The file does not exist

Here's how you can use themRutalibModule to check if the file exists.

Use Glob to check if the file exists

IsGlobal ModuleIn Python, you can access the file system.

The main benefit of usingGlobusModulo is pattern matching. You can also use this method to check if a file exists without using exceptions.

To check if the file exists, use theGlobus ()Method available in the global module.

Accepts the file path information.

Where from,

  • absolute path– If you want to check whether a file exists in another directory.
    Ö
  • filename– If you want to check the file in the current directory.

Returns

  • RIGHT– If the file existsjreadable
  • NOT CORRECT– If the file does not existÖit cannot be read

Use:If heglob.globis used outsideAND, a list of files matching the passed condition is returned.

Rest

import globif glob.glob("C:/temp/Test_Folder/test.txt"): print ("Existe un archivo")

Production

The file exists

This is how you can use the glob module to check whether a file exists.

You learned about the different methods available to check if a file exists in Python.

Check if a hidden file exists

You can check if the hidden file exists by typing theglob.globmodule or thatos.rutaModule. Both methods are shown below.

It is similar to checking regular files. Only the files are hidden.

Fragment with glob

import globif glob.glob("C:/temp/Test_Folder/hidden_file.txt"): print ("El archivo existe")

To test on Windows, we hide the file on Windows and run the above script. We saw the next exit. therefore the sameGlobusThe module can be used to check whether the hidden file exists or not.

Production

(Video) A Practical Approach to Kaggle Competition | DataHour | Analytics Vidhya

The file exists

Fragment with os.path

Use theexists()method available in theos.rutaModule to check if the hidden file exists.

from os import pathpath.exists("C:/temp/Test_Folder/hidden_file.txt")

Production

RIGHT

This is how you can check if a hidden file exists.

Check if the list contains multiple files

This section shows you how to check if multiple files exist in a specific directory.

You create a list of files.

You can use the list comprehension to verify that the file containing the existsos.ruta.isfile(f).

Returns a new list where contains

  • RIGHT– Whether the file exists.
  • NOT CORRECT– If the file does not exist.

So you can use thoseatFunction to check if all iterables are presentRIGHT.
All functions return

  • RIGHT– If all are iterablesRIGHTon the list
  • NOT CORRECT– If at least one iterable inNOT CORRECTon the list. This means that at least one file does not exist.

Rest

An example where all files are present.

import osfilelist = ['C:/temp/Test_Folder/file1.txt', 'C:/temp/Test_Folder/file2.txt', 'C:/temp/Test_Folder/test.txt']if all([os.path .isfile(f) für f in Dateiliste]): print("Todos los archivos existen") else: print("Todos los archivos existen")

Production

all files exist

Fragment 2

An example where at least one file does not exist.

import osfilelist = ['C:/temp/Test_Folder/file3.txt', 'C:/temp/Test_Folder/file2.txt', 'C:/temp/Test_Folder/test.txt']if all([os.path .isfile(f) für f in Dateiliste]): print("Todos los archivos existen") else: print("Todos los archivos existen")

Production

All files do not exist

So you can check whether there are multiple files in the list or not.

Verify that the regular expression file exists

In this section, you will check if files exist by checking theregular sentenceor pattern.

(Video) Knowledge Graph Solutions using Neo4j

It is also known as checking if a file exists using wildcards.

As seen before, for theFile access operation with pattern matching, you needUse the global module.

Use the following snippet to verify that the file starts with the nameoffice hoursexists in the directory.

Rest

import globif glob.glob('C:/temp/Test_Folder/file*.txt'): print("File exists with initial string file")

andat least one text file existsin the directory starting with textoffice hours, then you will see the following output.

Production

The file exists with the start string file

This is how you can use the regular expression to check if a file exists.

Check if the file exists in the subdirectory

To check if a file exists in the subdirectory, you can directly use the subdirectory information along with the file name as shown below.

The path.exists() method returns

  • RIGHT– If the file exists
  • NOT CORRECT– If the file does not exist in the subdirectory

Rest

vom Betriebssystem import pathpath.exists ("temp/temp.txt")

Production

RIGHT

So you can check if the file exists in the subdirectory.

Check if the file with the extension exists

To check if a file has a specific extension, you can use the regular expression withGlobus.

This is useful when you want to check if a file type exists in the directory.

Use the*.htmlif you want to check if an HTML file exists in the directory.

Rest

import globif glob.glob('*.html'): print("HTML file exists")

Production

(Video) Building Data Pipelines on GCP #googlecloud #datapipelines #data

HTML file exists

This is how you can check if a specific file type exists in the directory.

Conclusion

In summary, you learned about the different methods available in Python to check if a file exists. You also learned how to use the different methods in different use cases to verify the existence of the file in different scenarios.

If you have any questions, please comment below.

You may also like

  • How to list files in a directory in Python?
  • How to read binaries in Python?
  • How to read a file line by line in Python?

Videos

1. Easy pairing and shell session sharing with tmate
(tutoriaLinux)
2. Dinosaur! If you touch surprise egg, turn into Spider-Man! #DuDuPopTOY
(DuDuPopTOY)
3. Multi-Objective Optimisation
(Analytics Vidhya)
4. Python Programming Demo Class: Jupiter Vidya
(Jupiter Vidya)
5. Kubernetes: Beginner to Intermediate Session 3
(CloudMon)
6. The Data Hour: An Overview of Feature Engineering for Data Science
(Analytics Vidhya)
Top Articles
Latest Posts
Article information

Author: Tish Haag

Last Updated: 03/22/2023

Views: 5900

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Tish Haag

Birthday: 1999-11-18

Address: 30256 Tara Expressway, Kutchburgh, VT 92892-0078

Phone: +4215847628708

Job: Internal Consulting Engineer

Hobby: Roller skating, Roller skating, Kayaking, Flying, Graffiti, Ghost hunting, scrapbook

Introduction: My name is Tish Haag, I am a excited, delightful, curious, beautiful, agreeable, enchanting, fancy person who loves writing and wants to share my knowledge and understanding with you.