pathlib Python
Introduction
To create temporary files and directories refer to the tempfile module,
and for high-level processing of files and directories refer to the module
shutil
.
Articles that go well with this one:
Files in Linux
Basics of working with files in Python
Official documentation
cwd()
You can get the current directory with the method cwd()
from pathlib import Path curr = Path.cwd() print(type(curr)) print(curr)
<class 'pathlib.PosixPath'> /mnt/c/Users/Andrei/sandbox/python/pathlib
stat()
With stat() you can get data about a file.
A small example of working with st_mtime together with the module
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))
1794942935.020916 2026-11-17 21:15:35.020916
cat cities.txt
Barcelona, Benalmadena, Cordoba, Malaga, Torremolinos
exists()
With exists() you can check that a file exists (an alternative is 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
Article author: Andrei Olegovich