🧸

【Python】pathlib Tutorial Simply

2024/04/28に公開

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

  1. Path Components:
    Accessing parent directories (path.parent)
    file names(path.name),
    file stems(path.stem),
    and file extensions(path.suffix).
  2. 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.
  3. Reading and Writing:
    Methods like write_text(), read_text, write_bytes(), and read_bytes() provide convenient ways to read and write files.
  4. Directory Iteration:
    Methods like iterdir() allow you to iterate over files and directories within a given path.
    Using iterdir() 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).
    ・Exapmle
    from 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.

Reference

Python Document: pathlib

Discussion