下面是一份 结构化、可直接复习与对照使用的 Python 文件操作完整总结。覆盖从基础到工程实践中最常用、最容易出错的部分,与你前面已经接触的 os.walk、扩展名统计等内容是完全衔接的。


Python 文件相关操作总结


一、文件与目录的基本概念

对象 说明
文件(file) 存储数据的最小单位
目录(directory) 用于组织文件和子目录
路径(path) 文件或目录的定位方式

路径类型

  • 绝对路径D:\data\test.txt
  • 相对路径./data/test.txt

二、文件读写(最核心)

1️⃣ 打开文件:open()

open(file, mode='r', encoding=None)

常用模式:

模式 含义
r 读取(默认)
w 写入(覆盖)
a 追加
rb / wb 二进制读 / 写

2️⃣ 推荐写法:with open

with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()

优点:

  • 自动关闭文件
  • 不易泄漏资源
  • 工程级标准写法

3️⃣ 读取方式

f.read()        # 全部内容
f.readline()    # 一行
f.readlines()   # 行列表

推荐:

for line in f:
    print(line.strip())

4️⃣ 写入方式

f.write("hello\n")
f.writelines(["a\n", "b\n"])

三、目录操作(os 模块)

1️⃣ 判断路径类型

os.path.exists(path)
os.path.isfile(path)
os.path.isdir(path)

2️⃣ 创建 / 删除目录

os.mkdir("dir")        # 单层
os.makedirs("a/b/c")   # 多层

os.rmdir("dir")        # 空目录

3️⃣ 列出目录内容

os.listdir(path)

4️⃣ 拼接路径(跨平台)

os.path.join(root, filename)

禁止手写:

root + "/" + filename  # ❌

四、遍历目录(重点)

1️⃣ os.walk()(递归)

for root, dirs, files in os.walk(path):
    ...
返回值 含义
root 当前目录路径
dirs 子目录名列表
files 文件名列表

控制递归:

dirs.remove("venv")

2️⃣ 只遍历一层

for root, dirs, files in os.walk(path):
    ...
    break

五、文件名与路径处理

1️⃣ 获取文件扩展名(标准)

name, ext = os.path.splitext(filename)

2️⃣ 文件大小 / 修改时间

os.path.getsize(path)
os.path.getmtime(path)

六、文件类型统计(综合示例)

from collections import defaultdict
import os

counter = defaultdict(int)

for root, _, files in os.walk(path):
    for f in files:
        _, ext = os.path.splitext(f)
        ext = ext.lower() if ext else 'no_extension'
        counter[ext] += 1

七、文件复制 / 删除 / 重命名

使用 shutil(更安全)

import shutil

shutil.copy(src, dst)
shutil.move(src, dst)
shutil.rmtree(dir_path)

八、使用 pathlib(现代写法)

from pathlib import Path

p = Path("data")

for file in p.rglob("*"):
    if file.is_file():
        print(file.suffix)

对比:

os pathlib
函数式 面向对象
老标准 新推荐
灵活 可读性强

九、输入输出与文件结合

path = input("请输入路径: ")

with open("result.txt", "w", encoding="utf-8") as f:
    f.write(str(result))

十、常见错误总结(重点)

错误 原因
文件未关闭 未用 with open
路径拼接错误 手写 /
编码报错 未指定 encoding
扩展名识别错 split('.')
重复遍历 os.walkbreak

十一、工程实践建议(你这个阶段非常重要)

  1. 路径处理统一用 os.path.joinpathlib
  2. 遍历目录首选 os.walk
  3. 文件扩展名用 splitext
  4. 统计类问题用 defaultdict / Counter
  5. 所有文件操作都包在 with open

十二、一句话记忆版

Python 文件操作 = open 读写 + os.walk 遍历 + os.path 处理路径

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐