47. Path Manipulation with os Module
Here are 10 Python code snippets demonstrating path manipulation using the os module, specifically focusing on the os.path submodule. These examples cover tasks like navigating, creating, and manipulating filesystem paths.
1. Joining Paths with os.path.join()
Combining multiple parts of a filesystem path into one complete path.
import os
path = os.path.join('folder', 'subfolder', 'file.txt')
print(f"Full path: {path}")This will combine 'folder', 'subfolder', and 'file.txt' into a single path, considering the operating system's path separator.
2. Getting the Absolute Path with os.path.abspath()
Converting a relative path into an absolute path.
import os
relative_path = 'folder/file.txt'
absolute_path = os.path.abspath(relative_path)
print(f"Absolute path: {absolute_path}")This will print the absolute path of the file.txt, resolving it from the current working directory.
3. Checking if a Path Exists with os.path.exists()
Verifying whether a specified path exists or not.
This checks if the file or directory at the given path exists.
4. Checking if a Path is a File with os.path.isfile()
Determining if a given path is a file.
This checks if the given path refers to a file.
5. Checking if a Path is a Directory with os.path.isdir()
Checking if the given path refers to a directory.
This checks if the path refers to a directory.
6. Getting the Directory Name with os.path.dirname()
Extracting the directory name from a given file path.
This will output 'folder/subfolder', which is the directory containing file.txt.
7. Getting the Base Name of a Path with os.path.basename()
Getting the final component of the path (either a file or directory name).
This will output 'file.txt', the final part of the path.
8. Splitting the Path into Directory and File Name with os.path.split()
Separating the directory path and the file name into two parts.
This splits the path into the directory ('folder/subfolder') and the file name ('file.txt').
9. Normalizing a Path with os.path.normpath()
Normalizing a path by collapsing redundant separators and up-level references.
This will remove redundant references and return 'folder/file.txt'.
10. Getting the File Extension with os.path.splitext()
Splitting the file name into the root and the extension.
This will output the root ('folder/subfolder/file') and the extension ('.txt').
These snippets demonstrate how to effectively manipulate filesystem paths using os.path, making it easier to navigate, check, and modify paths in Python programs.
Last updated