Питон проверить наличие файла

Python Check If File Exists

In this tutorial, you’ll learn how do I check if a file exists or not in Python.

Whenever we work with files, sometimes we need to check whether the file is present on a given path before performing any operation.

For example, if you are trying to copy content from one file into another file. In this case, we need to check if both files exist before executing this operation. It will raise a FileNotFound exception if the file is not present on the disk. Python has multiple ways to check whether a file exists with or without exception (without using the try statement).

In this article, We will use the following three methods of an OS and pathlib module.

os.path module:

  • os.path.isfile(‘file_path’) : Returns True if the path is a regular file.
  • os.path.exists(‘file_path’) : Returns True if the path is a file, directory, or a valid symlink.
  • os.path.isdir(‘file_path’) : Returns True if the path is a directory.

Pathlib module:

Table of contents

os.path.isfile() Method to Check If File Exists

For example, if you want to read a file to analyze the sales data to prepare a monthly report, we want to check whether we have a sales file with data in place to analyze it. If the file does not exist, we will need to create it.

Читайте также:  Java asm load class

The os.path module has some valuable functions on pathnames. Here we will see how to use the os.path module to check if a file exists.

  1. Important the os.path module This module helps us to work with file paths and directories in Python. Using this module, we can access and manipulate paths.
  2. Construct File Path A file path defines the location of a file or folder in the computer system. There are two ways to specify a file path.

Absolute path: which always begins with the root folder. The absolute path includes the complete directory list required to locate the file. For example, /user/Pynative/data/sales.txt is an absolute path to discover the sales.txt. All of the information needed to find the file is contained in the path string.

Relative path: which is relative to the program’s current working directory.

Example

In this example, we are looking for sales.txt.

import os.path # file to check file_path = r'E:/demos/files_demos/account/sales.txt' flag = os.path.isfile(file_path) if flag: print(f'The file exists') else: print(f'The file does not exist') # you can create it if required 
The file E:/demos/files_demos/account/sales.txt exists

The os.path.isfile() will return True only when the given path is a file path. If the given path is a directory, it will return False . If you want to check for both file/directory then use the os.path.exists(file_path) .

import os.path # file print(os.path.isfile(r'E:/demos/files_demos/account/sales.txt')) # Output True # Directory print(os.path.isfile(r'E:/demos/files_demos/account/')) # Output False # Directory print(os.path.exists(r'E:/demos/files_demos/account/')) # Output True

Also, this is the simplest way to check if a file exists. However, just because the file existed when you checked doesn’t guarantee that it will be there when you need to open it because if many applications or users are using it, there is a chance it could get deleted or moved after your check.

pathlib.Path.isfile() Method to Check If File Exists

From Python 3.4 onwards, we can use the pathlib module, which provides a wrapper for most OS functions. This module offers classes representing filesystem paths with semantics appropriate for different operating systems.

The pathlib module allows you to manipulate files and directories using the object-oriented approach. Let’s see how to use the pathlib module to check if a file exists.

  • First, import pathlib module
  • Next, Use pathlib.Path(‘file_path’) class to create a concrete path (location of the file). It will return the file path object.
  • At the end, execute the path.is_file() method to check if given file exists.
from pathlib import Path file_path = r'E:/demos/files_demos/account/sales.txt' # Path class path = Path(file_path) if path.is_file(): print(f'The file exists') else: print(f'The file does not exist') 

os.path.exists() Method to Check if File Exists

This function returns True if the path is a regular file, directory, or a valid symlink. If the given path is a directory path instead of a file, it will still return True because it checks only for a valid path.

import os.path file_path = r'E:/demos/files_demos/account/sales.txt' flag = os.path.exists(file_path) if flag: print(f'The file exists') else: print(f'The file does not exist') # directory flag = os.path.exists(r'E:/demos/files_demos/account/') if flag: print(f'The path exists') else: print(f'path does not exist') 
The file E:/demos/files_demos/account/sales.txt exists The path exists

Check If File Exists in a Directory or Subdirectories

Sometimes we need to check whether the file is present in a given directory or its subdirectories. Let’s see this with an example.

Example: check if ‘sale.txt’ exists in the reports folder and its subfolders.

  • We need to use Python glob module.
  • Set recursive=True to search inside all subdirectories. It is helpful If we are not sure exactly in which folder our search term or file is located. it recursively searches files under all subdirectories of the current directory.
import glob # glob to search sales.txt in account folder and all its subfolders for file in glob.glob(r'E:\demos\reports/**/sales.txt', recursive=True): if file: print(file, 'exists') else: print('file not exists')
E:\demos\reports\account\sales.txt exists

Check if Directory exists using os.path.isdir()

The os.path.isdir(path) function returns True if the path is a directory or a symlink to a directory.

import os.path # returns True or False if os.path.isdir(r'E:\demos\files'): print("Directory exist") else: print("Directory not exist")

Race Condition

Using the try statement, you simply attempt to read your file, expecting it to be there, and if not, you can catch the exception and perform the fallback operation.

But if you want to check a file exists before you attempt to read it, if multiple threads or applications are using the same file, there is a chance they might delete it after your file check. Therefore, it will increase the risk of a race condition.

When you find a file exists and attempt to read it. But after your checking and before reading, if a file gets deleted (its existence changes), you will get an exception.

Race conditions are very hard to debug because there’s a tiny window in which they can cause your program to fail.

Summary

The os.path module provides the following three more functions to check if a file or directory exists.

  • os.path.isfile(path) – Returns True if the path is a regular file or a symlink to a file.
  • os.path.exists(path) – Returns True if the path is a file, directory, or a valid symlink.
  • os.path.isdir(path) – Returns True if the path is a directory or a symlink to a directory.

Pathlib module provides a pathlib.Path(‘file_path’).isfile() function to check if the exists .

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Оцените статью