返回笔记列表

读写文件 + JSON:Python 处理数据的入门姿势

程序跑起来之后,总要和文件打交道:读配置、写日志、存数据。这篇讲 Python 最基础的文件操作和 JSON 处理,覆盖 90% 的日常场景。

一、写文件

最简单的方式

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, 世界\n")
    f.write("第二行\n")

模式说明

  • "w" — 写入(覆盖原有内容)
  • "a" — 追加(不覆盖,加到末尾)
  • "x" — 独占写入(文件已存在则报错)
💡 为什么用 with?不用 with 的话你得手动 f.close(),如果中间报错就漏关了。用 with 不管正常结束还是抛异常,文件都会自动关闭。

二、读文件

一次性读完

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

逐行读(大文件推荐)

with open("big.log", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())  # strip() 去掉换行符

读所有行到列表

with open("data.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()  # ['第一行\n', '第二行\n', ...]

三、JSON:最通用的数据格式

Python 对象 → JSON 字符串

import json

data = {
    "name": "小明",
    "age": 25,
    "skills": ["Python", "Linux"],
    "address": {"city": "上海", "zip": "200000"}
}

json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)

JSON 字符串 → Python 对象

json_str = '{"name": "小红", "score": 95}'
obj = json.loads(json_str)
print(obj["name"])   # 小红
print(obj["score"])  # 95

直接读写 JSON 文件

import json

# 写
with open("config.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# 读
with open("config.json", "r", encoding="utf-8") as f:
    data = json.load(f)

ensure_ascii=False 是什么意思

默认情况下 json.dumps 会把中文转成 \uXXXX。加 ensure_ascii=False 就保留中文原文,可读性好很多。

四、CSV:表格数据

import csv

# 写 CSV
with open("students.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["姓名", "分数", "等级"])
    writer.writerow(["小明", 95, "A"])
    writer.writerow(["小红", 82, "B"])

# 读 CSV
with open("students.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["姓名"], row["分数"])

五、实用组合:日志记录

import json
from datetime import datetime

def log_action(action, detail):
    """追加一条操作日志到 JSON Lines 文件"""
    entry = {
        "time": datetime.now().isoformat(),
        "action": action,
        "detail": detail
    }
    with open("actions.log", "a", encoding="utf-8") as f:
        f.write(json.dumps(entry, ensure_ascii=False) + "\n")

log_action("login", "用户小明登录")
log_action("upload", "上传了 report.pdf")

JSON Lines 格式

每行一个独立 JSON 对象,比大 JSON 数组更适合追加写入(不用每次读-改-写整个文件)。

六、路径处理

别用字符串拼路径,用 pathlib:

from pathlib import Path

p = Path("data") / "reports" / "2026"
p.mkdir(parents=True, exist_ok=True)  # 递归创建目录

file = p / "summary.json"
file.write_text(json.dumps(data, ensure_ascii=False))
print(file.read_text())