- Проверьте, существует ли файл или каталог в Python
- 1. Использование pathlib модуль
- 2. Использование os.path модуль
- 3. Использование open() функция
- How to Check if a File Exists in Python with isFile() and exists()
- How to Check if a File Exists Using the os.path Module
- How to Check if a File Exists Using the os.path.isfile() Method in Python
- How to Check if a File Exists Using the os.path.exists() Method in Python
- How to Check if a File Exists Using the pathlib Module
- How to Check if a File Exists Using the Path.is_file() Method in Python
- Conclusion
- Проверка наличия файла или каталога по указанному пути
Проверьте, существует ли файл или каталог в Python
В этом посте мы обсудим, как проверить, существует ли файл или каталог в Python.
1. Использование pathlib модуль
Начиная с Python 3.4, вы можете использовать pathlib модуль, который предлагает пути объектно-ориентированной файловой системы. Path.is_file() Функция проверяет, указывает ли путь на обычный файл.
Чтобы проверить существующий каталог, используйте Path.is_dir() функция:
Если вам нужно проверить, существует ли путь, независимо от того, является ли он файлом или каталогом, используйте Path.exists() функция:
2. Использование os.path модуль
Другим вариантом является использование os.path.isdir() функция для проверки существующего обычного файла.
Чтобы проверить существующий каталог, используйте os.path.isdir() функция:
Чтобы проверить, является ли данный путь существующим файлом или каталогом, используйте os.path.exists() функция:
3. Использование open() функция
В качестве альтернативы вы можете попытаться открыть данный файл и перехватить возникшее исключение, если оно не существует.
Это все, что касается определения того, существует ли файл или каталог в Python.
Средний рейтинг 4.77 /5. Подсчет голосов: 22
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно
How to Check if a File Exists in Python with isFile() and exists()
Dionysia Lemonaki
When working with files in Python, there may be times when you need to check whether a file exists or not.
But why should you check if a file exists in the first place?
Confirming the existence of a specific file comes in handy when you want to perform particular operations, such as opening, reading from, or writing to that file.
If you attempt to perform any of the operations mentioned above and the file doesn’t exist, you will come across bugs and your program will end up crashing.
So, to perform operations and prevent your program from crashing, it is a helpful first step to check if a file exists on a given path.
Thankfully, Python has multiple built-in ways of checking whether a file exists, like the built-in os.path and pathlib modules.
Specifically, when using the os.path module, you have access to:
- the os.path.isfile(path) method that returns True if the path is a file or a symlink to a file.
- the os.path.exists(path) method that returns True if the path is a file, directory, or a symlink to a file.
And when using the pathlib module, you have access to the pathlib.Path(path).is_file() function, which returns True if path is a file and it exists.
In this article, you will learn how to use Python to check if a file exists using the os.path and pathlib modules.
How to Check if a File Exists Using the os.path Module
The os module is part of the standard library (also known as stdlib ) in Python and provides a way of accessing and interacting with the operating system.
With the os module, you can use functionalities that depend on the underlying operating system, such as creating and deleting files and folders, as well as copying and moving contents of folders, to name a few.
Since it is part of the standard library, the os module comes pre-packaged when you install Python on your local system. You only need to import it at the top of your Python file using the import statement:
The os.path is a submodule of the os module.
It provides two methods for manipulating files — specifically the isfile() and exists() methods that output either True or False , depending on whether a file exists or not.
Since you will be using the os.path submodule, you will instead need to import that at the top of your file, like so:
How to Check if a File Exists Using the os.path.isfile() Method in Python
The general syntax for the isfile() method looks like this:
The method accepts only one argument, path , which represents the defined path to the file whose existence you want to confirm.
The path argument is a string enclosed in quotation marks.
The return value of the isfile() method is either a Boolean value — either True or False depending on whether that file exists.
Keep in mind that if the path ends in a directory name and not a file, it will return False .
Let’s see an example of the method in action.
I want to check whether an example.txt file exists in my current working directory, python_project .
The example.txt is on the same level as my Python file main.py , so I am using a relative file path.
I store the path to example.txt in a variable named path .
Then I use the isfile() method and pass path as an argument to check whether example.txt exists in that path.
Since the file does exist, the return value is True :
import os.path path = './example.txt' check_file = os.path.isfile(path) print(check_file) # output # True
Ok, but what about absolute paths?
Here is the equivalent code when using an absolute path. The example.txt file is inside a python_project directory, which is inside my home directory, /Users/dionysialemonaki/ :
import os.path path = '/Users/dionysialemonaki/python_project/example.txt' print(os.path.isfile(file_path)) # Output # True
And as mentioned earlier, the isfile() method only works for files and not directories:
import os.path path = '/Users/dionysialemonaki/python_project' check_file = os.path.isfile(path) print(check_file) # output # False
If your path ends in a directory, the return value is False .
How to Check if a File Exists Using the os.path.exists() Method in Python
The general syntax for the exists() method looks like this:
As you can see from the syntax above, the exists() method looks similar to the isfile() method.
The os.path.exists() method checks to see whether the specified path exists.
The main difference between exists() and isfile() is that exists() will return True if the given path to a folder or a file exists, whereas isfile() returns True only if the given path is a path to a file and not a folder.
Keep in mind that if you don’t have access and permissions to the directory, exists() will return False even if the path exists.
Let’s go back to the example from the previous section and check whether the example.txt file exists in the current working directory using the exists() method:
import os.path path = './example.txt' check_file = os.path.exists(path) print(check_file) # output # True
Since the path to example.txt exists, the output is True .
As mentioned earlier, the exists() method checks to see if the path to a directory is valid.
In the previous section, when I used the isfile() method and the path pointed to a directory, the output was False even though that directory existed.
When using the exists() method, if the path to a directory exists, the output will be True :
import os.path path = '/Users/dionysialemonaki/python_project' check_file = os.path.exists(path) print(check_file) # output # True
The exists() method comes in handy when you want to check whether a file or directory exists.
How to Check if a File Exists Using the pathlib Module
Python 3.4 version introduced the pathlib module.
Using the pathlib module to check whether a file exists or not is an object-oriented approach to working with filesystem paths.
Like the os.path module from earlier on, you need to import the pathlib module.
Specifically, you need to import the Path class from the pathlib module like so:
Then, create a new instance of the Path class and initialize it with the file path you want to check:
from pathlib import Path # create a Path object with the path to the file path = Path('./example.txt')
You can use the type() function to check the data type:
from pathlib import Path path = Path('./example.txt') print(type(path)) # output is a pathlib object #
This confirms that you created a Path object.
Let’s see how to use the pathlib module to check if a file exists using the is_file() method, one of the built-in methods available with the pathlib module.
How to Check if a File Exists Using the Path.is_file() Method in Python
The is_file() method checks if a file exists.
It returns True if the Path object points to a file and False if the file doesn’t exist.
Let’s see an example of how it works:
from pathlib import Path # create a Path object with the path to the file path = Path('./example.txt') print(path.is_file()) # output # True
Since the example.txt file exists in the specified path, the is_file() method returns True .
Conclusion
In this article, you learned how to check if a file exists in Python using the os.path and pathlib modules and their associated methods.
Hopefully, you have understood the differences between the modules and when to use each one.
Thank you for reading, and happy coding!
Проверка наличия файла или каталога по указанному пути
Бывает, что надо проверить корректность введенного пользователем адреса файла или каталога. Сделать это можно с помощью функции os.path.exists , которая возвращает true , если объект файловой системы существует, и false – если нет.
Функция os.path.isfile проверяет, является ли объект файлом, а os.path.isdir — является ли каталогом.
В приведенном ниже скрипте проверяется наличие объекта по указанному пользователем адресу, после этого проверяется файл это или каталог. В зависимости от типа объекта выводится информация.
# Скрипт проверяет наличие пути. # Если файл, то выводит его размер, даты создания, открытия и модификации. # Если каталог, выводит список вложенных в него файлов и каталогов. import os import datetime test_path = input('Введите адрес: ') if os.path.exists(test_path): if os.path.isfile(test_path): print('ФАЙЛ') print('Размер:', os.path.getsize(test_path) // 1024, 'Кб') print('Дата создания:', datetime.datetime.fromtimestamp( int(os.path.getctime(test_path)))) print('Дата последнего открытия:', datetime.datetime.fromtimestamp( int(os.path.getatime(test_path)))) print('Дата последнего изменения:', datetime.datetime.fromtimestamp( int(os.path.getmtime(test_path)))) elif os.path.isdir(test_path): print('КАТАЛОГ') print('Список объектов в нем: ', os.listdir(test_path)) else: print('Объект не найден')
В скрипте также используются функции os.path.getsize (возвращает размер файла), os.path.getctime (время создания), os.path.getatime (время последнего открытия), os.path.getmtime (дата последнего изменения). Метод datetime.datetime.fromtimestamp позволяет выводить время в местном формате.
В скрипте также используются функции os.path.getsize (возвращает размер файла), os.path.getctime (время создания), os.path.getatime (время последнего открытия), os.path.getmtime (дата последнего изменения). Метод datetime.datetime.fromtimestamp позволяет выводить время в местном формате.
Примеры выполнения программы:
Введите адрес: /home/pl/test.py ФАЙЛ Размер: 2 Кб Дата создания: 2021-10-14 19:55:58 Дата последнего открытия: 2022-04-21 08:21:00 Дата последнего изменения: 2021-10-14 19:55:58
Введите адрес: /home/pl/pas КАТАЛОГ Список объектов в нем: ['vk', 'theory', 'tasks']