Python 文件操作

12.1 打开与关闭文件

open() 函数

1
2
3
4
5
# 基本语法
file = open("filename", mode)

# 使用完毕后关闭
file.close()

文件模式

模式 说明
r 读取(默认)
w 写入(覆盖)
a 追加
x 创建(存在则报错)
b 二进制模式
t 文本模式(默认)
+ 读写模式

12.2 with 语句(推荐)

with 语句自动管理文件关闭,是最佳实践。

1
2
3
4
5
6
7
8
# 读取文件
with open("file.txt", "r") as f:
content = f.read()
# 文件自动关闭

# 写入文件
with open("file.txt", "w") as f:
f.write("Hello, World!")

12.3 读取文件

读取方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
with open("example.txt", "r") as f:
# read() - 读取全部内容
content = f.read()
print(content)

with open("example.txt", "r") as f:
# readline() - 读取一行
line1 = f.readline()
line2 = f.readline()
print(line1, line2)

with open("example.txt", "r") as f:
# readlines() - 读取所有行(列表)
lines = f.readlines()
for line in lines:
print(line.strip())

逐行读取(推荐大文件)

1
2
3
with open("large_file.txt", "r") as f:
for line in f:
print(line.strip())

12.4 写入文件

write() 方法

1
2
3
4
5
6
7
8
# 写入(覆盖)
with open("output.txt", "w") as f:
f.write("第一行\n")
f.write("第二行\n")

# 追加
with open("output.txt", "a") as f:
f.write("追加的内容\n")

writelines() 方法

1
2
3
4
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("output.txt", "w") as f:
f.writelines(lines)

12.5 文件路径操作

pathlib 模块(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from pathlib import Path

# 创建路径
p = Path("data/file.txt")

# 路径拼接
full_path = p.parent / "new_file.txt"

# 检查存在
print(p.exists())

# 检查类型
print(p.is_file())
print(p.is_dir())

# 获取信息
print(p.name) # file.txt
print(p.stem) # file
print(p.suffix) # .txt
print(p.parent) # data

# 创建目录
Path("new_dir").mkdir(exist_ok=True)

# 列出文件
for file in Path(".").iterdir():
print(file.name)

os.path 模块

1
2
3
4
5
6
7
8
9
10
import os

path = "data/file.txt"

print(os.path.exists(path))
print(os.path.isfile(path))
print(os.path.isdir(path))
print(os.path.basename(path)) # file.txt
print(os.path.dirname(path)) # data
print(os.path.join("data", "file.txt")) # data/file.txt

12.6 JSON 文件处理

写入 JSON

1
2
3
4
5
6
7
8
9
10
import json

data = {
"name": "Alice",
"age": 25,
"skills": ["Python", "JavaScript"]
}

with open("data.json", "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)

读取 JSON

1
2
3
4
5
6
7
import json

with open("data.json", "r") as f:
data = json.load(f)

print(data["name"]) # Alice
print(data["skills"]) # ['Python', 'JavaScript']

JSON 字符串

1
2
3
4
5
6
7
8
9
10
import json

# 字典转 JSON 字符串
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)

# JSON 字符串转字典
parsed = json.loads(json_str)
print(parsed)

12.7 CSV 文件处理

写入 CSV

1
2
3
4
5
6
7
8
9
10
11
12
import csv

data = [
["Name", "Age", "City"],
["Alice", 25, "Beijing"],
["Bob", 30, "Shanghai"],
["Charlie", 22, "Guangzhou"]
]

with open("data.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(data)

读取 CSV

1
2
3
4
5
6
7
8
9
10
11
12
import csv

with open("data.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)

# 使用 DictReader
with open("data.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["Name"], row["Age"])

12.8 异常处理

文件操作可能抛出异常,需要处理。

1
2
3
4
5
6
7
8
9
try:
with open("nonexistent.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("文件不存在")
except PermissionError:
print("没有权限")
except Exception as e:
print(f"发生错误: {e}")

12.9 实用示例

统计文件行数

1
2
3
4
5
def count_lines(filename):
with open(filename, "r") as f:
return sum(1 for _ in f)

print(count_lines("example.txt"))

复制文件

1
2
3
4
5
6
def copy_file(src, dst):
with open(src, "rb") as f_src:
with open(dst, "wb") as f_dst:
f_dst.write(f_src.read())

copy_file("source.txt", "copy.txt")

查找文件中包含关键词的行

1
2
3
4
5
6
7
8
9
10
11
def search_file(filename, keyword):
results = []
with open(filename, "r") as f:
for i, line in enumerate(f, 1):
if keyword in line:
results.append((i, line.strip()))
return results

matches = search_file("log.txt", "ERROR")
for line_num, content in matches:
print(f"第 {line_num} 行: {content}")

12.10 本章小结

  • 使用 with open() 自动管理文件关闭
  • 读取方法:read()readline()readlines()
  • 写入方法:write()writelines()
  • pathlib 是现代路径操作推荐方式
  • JSON 使用 json.dump()json.load()
  • CSV 使用 csv.writercsv.reader
  • 文件操作需要异常处理

练习题

  1. 编写程序读取文件,统计单词出现频率
  2. 将字典数据保存为 JSON 文件,再读取并打印
  3. 创建 CSV 文件存储学生成绩,计算平均分
  4. 编写程序合并两个文本文件的内容
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
Python基础教程 系列
第 12/20 篇
分享: