pathlib Python

Содержание
Введение
cwd()
stat(): Метаданные
stem(): Отделить имя файла
exists(): Проверка существования
Похожие статьи

Введение

Для создания временных файлов и каталогов обратитесь к модулю tempfile, а для высокоуровневой обработки файлов и каталогов обратитесь к модулю shutil .

Статьи, которые хорошо дополняют эту:

Файлы в Linux

Основы работы с файлами в Python

Официальная документация

cwd()

Получить текущую директорию можно методом cwd()

from pathlib import Path curr = Path.cwd() print(type(curr)) print(curr)

<class 'pathlib.PosixPath'> /mnt/c/Users/Andrei/sandbox/python/pathlib

stat()

С помощью stat() можно получить данные о файле.

Небольшой пример работы с st_mtime при участии модуля datetime

from pathlib import Path from datetime import datetime with open("cities.txt", "w") as f: f.write("Barcelona, Benalmadena, Cordoba, Malaga, Torremolinos") file = Path("cities.txt") file_stat = file.stat() print(file_stat.st_mtime) print(datetime.fromtimestamp(file_stat.st_mtime))

1791911182.020916 2026-10-13 20:06:22.020916

cat cities.txt

Barcelona, Benalmadena, Cordoba, Malaga, Torremolinos

stem()

С помощью stem() можно отделить имя файла от расширения

from pathlib import Path print(Path("openapi.yaml").stem)

openapi

exists()

С помощью exists() можно проверить существование файла (альтернатива - os.path.exists())

from pathlib import Path with open("vpns.txt", "w") as f: f.write("AtlasVPN, beget, TurboVPN") file = Path("vpns.txt") print(Path("vpns.txt").exists()) # True

python pathlib_ex.py

True

cat vpns.txt

AtlasVPN, beget, TurboVPN

Article author: Andrei Olegovich

Похожие статьи
Основы Python
configparser
docstring
#!: Shebang
Объекты
Итерация
os
pathlib

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: