Fundamentals 6 min read

Using Python's os, os.path, pathlib, and tempfile Modules for File System Operations

This article demonstrates how to use Python's os, os.path, pathlib, and tempfile modules to retrieve the current working directory, list and manipulate files and directories, construct and normalize paths, and create temporary files and directories, providing clear code examples for each operation.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using Python's os, os.path, pathlib, and tempfile Modules for File System Operations

The

import os
current_directory = os.getcwd()
print(f"当前目录: {current_directory}")

snippet shows how to obtain the current working directory using the os module.

Subsequent examples illustrate listing directory contents (

files = os.listdir(current_directory)
print(f"目录中的文件: {files}")

), joining paths (

path = os.path.join(current_directory, 'subdir', 'file.txt')
print(f"拼接后的路径: {path}")

), splitting paths (

directory, filename = os.path.split(path)
print(f"目录: {directory}, 文件名: {filename}")

), extracting filename and extension (

filename, extension = os.path.splitext(filename)
print(f"文件名: {filename}, 扩展名: {extension}")

), checking existence (

exists = os.path.exists(path)
print(f"路径存在: {exists}")

), and determining if a path is a file or directory (

is_file = os.path.isfile(path)
is_dir = os.path.isdir(directory)
print(f"是否为文件: {is_file}, 是否为目录: {is_dir}")

).

Directory creation and removal are demonstrated with

new_directory = os.path.join(current_directory, 'new_subdir')
os.makedirs(new_directory, exist_ok=True)
print(f"创建目录: {new_directory}")
os.rmdir(new_directory)
print(f"删除目录: {new_directory}")

.

The os.path module provides additional utilities such as normalizing paths (

normalized_path = os.path.normpath(path)
print(f"规范化后的路径: {normalized_path}")

), obtaining absolute paths (

absolute_path = os.path.abspath(path)
print(f"绝对路径: {absolute_path}")

), retrieving the parent directory (

parent_directory = os.path.dirname(path)
print(f"父目录: {parent_directory}")

), getting the basename (

basename = os.path.basename(path)
print(f"文件的基本名: {basename}")

), and checking if a path is absolute (

is_absolute = os.path.isabs(path)
print(f"路径是否为绝对路径: {is_absolute}")

).

The pathlib module offers an object‑oriented approach: creating a Path object (

from pathlib import Path
current_directory = Path('.')
print(f"当前目录: {current_directory}")

), joining paths using the division operator (

path = current_directory / 'subdir' / 'file.txt'
print(f"拼接后的路径: {path}")

), splitting (

directory = path.parent
filename = path.name
print(f"目录: {directory}, 文件名: {filename}")

), extracting stem and suffix (

stem = path.stem
suffix = path.suffix
print(f"文件名: {stem}, 扩展名: {suffix}")

), checking existence and type (

exists = path.exists()
print(f"路径存在: {exists}")
is_file = path.is_file()
is_dir = path.is_dir()
print(f"是否为文件: {is_file}, 是否为目录: {is_dir}")

), normalizing (

normalized_path = path.resolve()
print(f"规范化后的路径: {normalized_path}")

), and obtaining parent and absolute paths (

parent_directory = path.parent
print(f"父目录: {parent_directory}")
absolute_path = path.absolute()
print(f"绝对路径: {absolute_path}")

).

Creating and deleting directories with pathlib is shown via

new_directory = current_directory / 'new_subdir'
new_directory.mkdir(exist_ok=True)
print(f"创建目录: {new_directory}")
new_directory.rmdir()
print(f"删除目录: {new_directory}")

.

Relative and absolute path handling using path.relative_to(current_directory) and path.absolute() is demonstrated, and temporary files and directories are managed with the tempfile module (

import tempfile
with tempfile.TemporaryFile() as temp:
    temp.write(b'Some data')
    temp.seek(0)
    print(temp.read().decode('utf-8'))
with tempfile.TemporaryDirectory() as temp_dir:
    print(f"临时目录: {temp_dir}")

).

In summary, the os module provides basic OS interaction, os.path extends path manipulation, pathlib offers an intuitive object‑oriented interface, and tempfile facilitates creation of temporary files and directories.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

pathlibtempfilefile-handlingos-module
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.