Python 基础:文件操作
5.1 文件读写
python
# 读取文件
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read() # 读取全部
# f.readline() # 读取一行
# f.readlines() # 读取所有行到列表
# 写入文件
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("第二行")
# 追加模式
with open("log.txt", "a", encoding="utf-8") as f:
f.write("新的日志内容\n")1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
5.2 JSON 操作
python
import json
# 写入 JSON
data = {"name": "Alice", "age": 25, "scores": [90, 85, 92]}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 读取 JSON
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(data["name"]) # Alice
# 字符串 ↔ JSON
json_str = json.dumps(data, ensure_ascii=False)
data2 = json.loads(json_str)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
5.3 Pathlib(推荐方式)
python
from pathlib import Path
# 路径操作
p = Path(".") / "subdir" / "file.txt"
print(p) # subdir/file.txt
print(p.parent) # subdir
print(p.stem) # file
print(p.suffix) # .txt
# 读写文件
p.write_text("Hello", encoding="utf-8")
content = p.read_text(encoding="utf-8")
# 目录操作
Path("new_dir").mkdir(exist_ok=True) # 创建目录
Path("old_dir").rmdir() # 删除空目录
# 遍历目录
for f in Path(".").iterdir():
print(f.name)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
5.4 CSV 操作
python
import csv
# 写入 CSV
with open("data.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "age", "city"])
writer.writeheader()
writer.writerows([
{"name": "Alice", "age": 25, "city": "Beijing"},
{"name": "Bob", "age": 30, "city": "Shanghai"},
])
# 读取 CSV
with open("data.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["age"])1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[[返回 Python 首页|python/index]]