Processing file paths in Python
Here is a detailed introduction to how to use itpathlib
Module to process file paths. We will createPath
Explained on several aspects such as object, absolute path and relative path, accessing file path components, and checking whether the file path exists.
1. Create a Path object
To usepathlib
, first you need to import the module and create aPath
Object.
from pathlib import Path # Create a Path object representing the current working directorycurrent_directory = () print(f"Current working directory: {current_directory}") # Create a Path object representing a specific filefile_path = Path("") print(f"Specify file path: {file_path}")
2. Absolute path and relative path
- Absolute pathRefers to the complete path starting from the root directory.
- Relative pathis the path relative to the current working directory.
# Get the absolute pathabsolute_path = file_path.resolve() print(f"Absolute path: {absolute_path}") # Create Path object using relative pathsrelative_path = Path("subfolder/") print(f"Relative path: {relative_path}")
3. Access file path components
Path
Objects provide some properties and methods for accessing different parts of the file path.
# Analyze file pathsprint(f"file name: {file_path.name}") # file nameprint(f"File suffix: {file_path.suffix}") # File extensionprint(f"file name(Without extension): {file_path.stem}") # File name without extensionprint(f"Parent directory: {file_path.parent}") # Parent directoryprint(f"Root directory: {file_path.anchor}") # root directory (drive letters on Windows)
4. Check whether the file path exists
Can be usedexists()
Methods to check whether a file or directory exists, and there are other useful methods.
# Check if the file existsif file_path.exists(): print(f"{file_path} The file exists") else: print(f"{file_path} The file does not exist") # Check if it is a fileif file_path.is_file(): print(f"{file_path} It's a file") elif file_path.is_dir(): print(f"{file_path} It's a directory") else: print(f"{file_path} Neither a file nor a directory")
5. Other practical methods
pathlib
Many other useful methods are also provided, such as traversing directories, reading file contents, etc.
Iterate through all files in the directory
# List all files and subdirectories in the current directoryfor item in current_directory.iterdir(): print(item)
Read file content
# Read the file content (make sure the file exists)if file_path.exists() and file_path.is_file(): with file_path.open('r') as f: content = () print(content)
summary
-
Create
Path
ObjectusePath()
To represent a file or directory. -
Absolute path vs. Relative pathCan be passed
resolve()
Method gets the absolute path. -
Access file path componentsVarious attributes can be used such as
.name
,.suffix
,.stem
,.parent
wait. -
Check if the file path existsCan be used
exists()
,is_file()
,is_dir()
etc.
usepathlib
It can make file path operation more concise and clear, and it is very suitable for modern Python programming.
This is the article about how Python uses the pathlib module to process file paths. For more related contents of Python pathlib processing file paths, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!