Fundamentals 4 min read

Using Python’s os, sys, and os.path Modules: Common Operations and Code Examples

This article introduces Python’s os, sys, and os.path modules, demonstrating how to retrieve the current working directory, create and delete directories, list files, execute system commands, access interpreter information, handle command‑line arguments, redirect I/O, and manipulate file paths with practical code snippets.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using Python’s os, sys, and os.path Modules: Common Operations and Code Examples

The os module provides functions for interacting with the operating system, such as retrieving the current working directory, creating and deleting directories, listing directory contents, and executing system commands.

import os
# 获取当前的工作目录
current_directory = os.getcwd()
print("当前工作目录:", current_directory)
# 创建一个新目录
os.mkdir('新建文件夹')
print("已创建目录")
# 列出指定目录的内容
files = os.listdir('.')
print("当前目录下的文件和文件夹:", files)
# 删除之前创建的目录
os.rmdir('新建文件夹')
print("目录已删除")
# 执行系统命令并获取结果
result = os.system('echo Hello World')
print("执行系统命令的结果:", result)

The sys module gives access to interpreter variables and functions, allowing you to print the Python version, exit the program, read command‑line arguments, redirect standard output, and query the maximum integer size.

import sys
# 打印Python解释器的版本信息
print("Python版本:", sys.version)
# 退出Python程序
sys.exit("程序正常退出")
# 打印从命令行传递给脚本的参数
print("命令行参数:", sys.argv)
# 将输出重定向到一个文件
temp = sys.stdout
sys.stdout = open('log.txt', 'w')
print("这将被写入log.txt")
sys.stdout.close()
sys.stdout = temp
print("标准输出已恢复")
# Python中可处理的最大整数值
print("Python支持的最大整数:", sys.maxsize)

The os.path submodule offers utilities for file‑path manipulation, including joining paths, checking existence, determining file type, obtaining file size, and retrieving absolute paths.

# 使用os.path.join()安全地组合路径
path = os.path.join('用户', '文档', '文件.txt')
print("组合后的路径:", path)
# 检查某个路径是否存在
exists = os.path.exists('.')
print("路径存在吗:", exists)
# 检查路径是否指向一个文件
is_file = os.path.isfile('test.py')  # 假设'test.py'是存在的
print("这是一个文件吗:", is_file)
# 获取文件的大小(以字节为单位)
size = os.path.getsize('test.py')  # 假设'test.py'是存在的
print("文件大小:", size, "字节")
# 获取文件的绝对路径
abs_path = os.path.abspath('test.py')  # 假设'test.py'是存在的
print("文件的绝对路径:", abs_path)
Pythonos modulefile handlingos.pathsys moduleSystem Commands
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login 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.