Python 3 pathlib проверка существования файла

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.

Читайте также:  Working with calendar java

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

Источник

Как проверить, существует ли файл или каталог в Python

При написании скриптов Python вы можете захотеть выполнить определенное действие, только если файл или каталог существует или нет. Например, вы можете захотеть прочитать или записать данные в файл конфигурации или создать файл, только если он уже не существует.

В Python есть много разных способов проверить, существует ли файл, и определить его тип.

В этом руководстве показаны три различных метода проверки существования файла.

Проверьте, существует ли файл

Самый простой способ проверить, существует ли файл, — это попытаться открыть файл. Этот подход не требует импорта какого-либо модуля и работает как с Python 2, так и с Python 3. Используйте этот метод, если вы хотите открыть файл и выполнить какое-либо действие.

В следующем фрагменте кода используется простой блок try-except. Мы пытаемся открыть файл filename.txt , и если файл не существует, возникает исключение IOError и IOError сообщение «Файл недоступен»:

try: f = open("filename.txt") # Do something with the file except IOError: print("File not accessible") finally: f.close() 

Если вы используете Python 3, вы также можете использовать FileNotFoundError вместо исключения IOError .

При открытии файлов рекомендуется использовать ключевое слово with , которое обеспечивает правильное закрытие файла после завершения файловых операций, даже если во время операции возникает исключение. Это также делает ваш код короче, потому что вам не нужно закрывать файл с помощью функции close .

Следующий код эквивалентен предыдущему примеру:

try: with open('/etc/hosts') as f: print(f.readlines()) # Do something with the file except IOError: print("File not accessible") 

В приведенных выше примерах мы использовали блок try-except и открывали файл, чтобы избежать состояния гонки. Условия состязания возникают, когда к одному файлу обращается более одного процесса.

Например, когда вы проверяете наличие файла, другой процесс может создать, удалить или заблокировать файл в период времени между проверкой и открытием файла. Это может привести к поломке вашего кода.

Проверьте, существует ли файл с помощью модуля os.path

Модуль os.path предоставляет несколько полезных функций для работы с os.path путей. Модуль доступен как для Python 2, так и для 3.

В контексте этого руководства наиболее важными функциями являются:

  • os.path.exists(path) — возвращает true, если path — это файл, каталог или допустимая символическая ссылка.
  • os.path.isfile(path) — возвращает истину, если path является обычным файлом или символической ссылкой на файл.
  • os.path.isdir(path) — возвращает true, если path является каталогом или символической ссылкой на каталог.

Следующий оператор if проверяет, существует ли файл filename.txt :

import os.path if os.path.isfile('filename.txt'): print ("File exist") else: print ("File not exist") 

Используйте этот метод, когда вам нужно проверить, существует ли файл или нет, прежде чем выполнять действие с файлом. Например, копирование или удаление файла .

Если вы хотите открыть и изменить файл, используйте предыдущий метод.

Проверьте, существует ли файл, используя модуль pathlib

Модуль pathlib доступен в Python 3.4 и выше. Этот модуль предоставляет объектно-ориентированный интерфейс для работы с путями файловой системы для различных операционных систем.

Как и в предыдущем примере, следующий код проверяет, существует ли файл filename.txt :

from pathlib import Path if Path('filename.txt').is_file(): print ("File exist") else: print ("File not exist") 

is_file возвращает истину, если path является обычным файлом или символической ссылкой на файл. Чтобы проверить наличие каталога, используйте метод is_dir .

Основное различие между pathlib и os.path заключается в том, что pathlib позволяет вам работать с путями как с объектами Path с соответствующими методами и атрибутами вместо обычных объектов str .

Если вы хотите использовать этот модуль в Python 2, вы можете установить его с помощью pip :

Выводы

В этом руководстве мы показали вам, как с помощью Python проверить, существует ли файл или каталог.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

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