Python 中的文件处理与系统模块详解

Python 提供了丰富的文件处理和系统相关模块,这些模块使得文件操作、目录管理以及与操作系统的交互变得简单而强大。在本文中,我们将深入探讨其中一些重要的模块和它们的用法。

1. os 模块:操作系统相关功能

os 模块提供了与操作系统交互的功能,可以执行文件和目录操作、获取系统信息等。

示例 1:获取当前工作目录和修改目录

python 复制代码
import os

current_directory = os.getcwd()
print("Current Directory:", current_directory)

os.chdir('/path/to/new/directory')
print("Changed Directory:", os.getcwd())

示例 2:遍历目录并打印文件名

python 复制代码
for root, dirs, files in os.walk('/path/to/directory'):
    for file in files:
        print(os.path.join(root, file))

2. shutil 模块:高级文件操作

shutil 模块提供了更高级的文件操作,包括文件复制、移动、删除等功能。

示例 3:复制文件夹及其内容

python 复制代码
import shutil

source = '/path/to/source_folder'
destination = '/path/to/destination_folder'

shutil.copytree(source, destination)

3. sys 模块:与 Python 解释器交互

sys 模块提供了与 Python 解释器交互的功能,可访问解释器相关的变量和函数。

示例 4:获取命令行参数

python 复制代码
import sys

arguments = sys.argv
print("Command Line Arguments:", arguments)

4. pathlib 模块:面向对象的路径操作

pathlib 模块提供了面向对象的路径操作,使得路径处理更加直观和易用。

示例 5:路径拼接和文件操作

python 复制代码
from pathlib import Path

file_path = Path('/path/to/directory') / 'file.txt'
print("File Exists:", file_path.exists())

# 读取文件内容
if file_path.exists():
    with open(file_path, 'r') as file:
        content = file.read()
        print("File Content:", content)

5. subprocess 模块:调用外部命令

subprocess 模块允许在 Python 中调用外部命令,执行系统命令并获取输出。

示例 6:执行系统命令并获取输出

复制

python 复制代码
import subprocess

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print("Command Output:", result.stdout)

以上示例展示了 Python 中文件处理和系统相关模块的一些基本功能和用法。这些模块提供了广泛的功能,使得文件和系统操作变得更加简单和灵活。

相关推荐
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技2 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊3 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1233 天前
2026年第38周GitHub趋势周报
python·科技·github
IZero073 天前
Jev 与 Laya
python·语言模型