🧸
【Python】pathlib Tutorial Simply
1. pathlib
pathlib is a python module that provides an object-oriented iterface for working with file system paths. It was introduced in Python3.4 and has become a popular choice for path manipulation due to its simplicity and flexibility.
2. Example Code
2.1 Example
Those are basic code of pathlib. It is very useful for treat thing rekated to path, please execute below in your environment and feel.
from pathlib import Path
# Create a Path object
path = Path("/home/user/documents/file.txt")
# Access path components
print("Absolute:", path.absolute()) # /home/user/documents/file.txt
print("Directory:", path.parent) # /home/user/documents
print("File name:", path.name) # file.txt
print("File stem:", path.stem) # file
print("File suffix:", path.suffix) # .txt
print("Without suffix:", path.absolute().with_suffix('')) # /home/user/documents/file
# Check if the path exists
print("Path exists?", path.exists()) # True/False
print("Current directory:", path.cwd()) # [current directory]
# Create a new directory
new_dir = Path("/home/user/new_folder")
new_dir.mkdir(exist_ok=True) # Create directory, ignore if it already exists
# Create a new file and write content
new_file = new_dir / "new_file.txt" # Join paths
new_file.write_text("Hello, Pathlib!") # Write text to the file
# Read content from a file
print("File content:", new_file.read_text()) # "Hello, Pathlib!"
new_file_2 = new_dir / "new_file_2.txt"
new_file_2.write_text("Hi, Pathlib!")
# List all files in a directory
documents_path = Path("/home/user/new_folder")
for file in documents_path.iterdir(): # Iterate over all items in the directory
print("File in documents:", file.name)
# Removing file
file_path = new_dir / "new_file.txt"
file_path.unlink()
2.2 Common Methods
- Path Components:
Accessing parent directories (path.parent
)
file names(path.name
),
file stems(path.stem
),
and file extensions(path.suffix
). - Path Operations:
Joining paths(path / "subdirectory"
),
checking existence(path.exists()
),
checking current directory(path.cwd()
)
creating directories(path.mkdir()
),
removing files(path.unlink()
) or (path.remove()
),
and more. - Reading and Writing:
Methods likewrite_text()
,read_text
,write_bytes()
, andread_bytes()
provide convenient ways to read and write files. - Directory Iteration:
Methods likeiterdir()
allow you to iterate over files and directories within a given path.
Usingiterdir()
and.glob
together provide more efficiency.
※.glob
is typically used with directories to list files(It can also be used with file paths to find specific matches).
・Exapmlefrom pathlib import Path # Directory to list directory_path = Path("/path/to/directory") # Iterate over all items in the directory for item in directory_path.iterdir(): if item.is_file(): # If the item is a file, show the name print("File:", item.name) elif item.is_dir(): # If the item is a directory, list all Python files in it for py_file in item.glob("*.py"): print("Python file in subdirectory:", py_file.name)
3. Summary
With pathlib
, working with file paths becomes cleaner, reducing the need for complex string manipulations and increasing code readability.
Discussion