Skip to content

第 07 章 · 输入输出与文件读写 ​

本章目标 ​

把数据漂亮地打印出来、写进文件、再从文件读回来,会用 JSON 保存结构化数据。

7.1 print 不只是打印 ​

python
print("a", "b", "c")                 # a b c    (默认空格分隔)
print("a", "b", sep="-")             # a-b
print("处理中...", end="")            # 不换行
print("完成")

7.2 四种格式化写法 ​

python
name, score = "小明", 92.5

# ① f-string:推荐,最直观
print(f"{name} 得分 {score:.1f}")

# ② str.format()
print("{} 得分 {:.1f}".format(name, score))

# ③ 手动拼接/对齐(做表格用)
print(f"{name:<10}|{score:>8.2f}")
#  < 左对齐,> 右对齐,^ 居中,数字是宽度

# ④ 老式 % 写法(看老代码会遇到)
print("%s 得分 %.1f" % (name, score))

常用的还有:{n:,} 千分位、{p:.1%} 百分比、{x:08.2f} 补零。

7.3 文件读写:open + with ​

python
# 写
with open("demo.txt", "w", encoding="utf-8") as f:
    f.write("第一行\n")
    f.write("第二行\n")

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

with 是标准写法:块结束后自动关闭文件,哪怕中间出错也会关。

读取的三种方式:

python
with open("demo.txt", encoding="utf-8") as f:
    text = f.read()            # 一次读全部(小文件)
    # line = f.readline()      # 读一行
    # lines = f.readlines()    # 读成列表,每项一行

with open("demo.txt", encoding="utf-8") as f:
    for line in f:             # 大文件推荐:逐行
        print(line.rstrip())   # rstrip 去掉行尾换行

模式表:

模式含义注意
r只读(默认)文件不存在报错
w只写会清空原内容!
a追加在末尾加,不清空
x新建写入文件已存在报错
rb / wb二进制读写图片、压缩包用

三种写法对比 ​

python
# 追加
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("2026-09-18 启动成功\n")

# 一次写多行
with open("lines.txt", "w", encoding="utf-8") as f:
    f.writelines(["a\n", "b\n", "c\n"])

# 二进制复制文件
with open("logo.png", "rb") as src, open("logo_copy.png", "wb") as dst:
    dst.write(src.read())

7.4 JSON:保存"结构化数据" ​

JSON 就是带格式的文本,用来存字典/列表:

python
import json

data = {
    "name": "小明",
    "age": 18,
    "skills": ["Python", "Excel"],
}

# 写(ensure_ascii=False 才能正常显示中文)
with open("user.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# 读
with open("user.json", encoding="utf-8") as f:
    loaded = json.load(f)

print(loaded["skills"][0])        # Python

字符串与 JSON 互转:

python
s = json.dumps(data, ensure_ascii=False)
back = json.loads(s)

⚠️ JSON 的键必须是字符串,值只能是:字符串 / 数字 / 布尔 / null / 数组 / 对象。元组和 set 不能直接存,要转换。

7.5 CSV:和 Excel 交换数据 ​

python
import csv

# 写
with open("scores.csv", "w", encoding="utf-8-sig", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["姓名", "成绩"])
    writer.writerow(["小明", 92])
    writer.writerow(["小红", 88])

# 读
with open("scores.csv", encoding="utf-8-sig") as f:
    for row in csv.reader(f):
        print(row)

用 utf-8-sig 是为了让 Excel 打开不乱码;newline="" 能避免 Windows 上多出空行。

7.6 路径问题(最常见的一类错误) ​

python
from pathlib import Path

base = Path(__file__).parent        # 脚本所在目录,比相对路径可靠
file = base / "data" / "a.txt"
file.parent.mkdir(parents=True, exist_ok=True)   # 目录不存在就建

print(file.exists())
print(file.stat().st_size)          # 文件大小(字节)

要点:

  • 用 pathlib,别手拼 "C:\\a\\b.txt",跨系统容易翻车
  • open("a.txt") 用的是当前工作目录,不是你脚本的位置——所以常出"明明文件在啊"的问题
  • 读中文文本时指定 encoding="utf-8";遇到别的编码(老 Windows 文件常是 GBK),用 encoding="gbk" 试

7.7 高频错点与修正 ​

现象原因解决
FileNotFoundError路径不对 / 文件不在工作目录用 Path(__file__).parent 拼绝对路径
UnicodeDecodeError文件不是 UTF-8 编码试 encoding="gbk",或用 errors="ignore"
文件内容被清空用了 "w" 模式想保留原内容用 "a"
中文写入 Excel 乱码编码不对用 utf-8-sig
程序开了很多文件句柄忘了关一律用 with

7.8 练一练 ​

  1. 让程序把用户输入的 3 句话追加写入 notes.txt,再读出来逐行打印,前面加行号。
  2. 把第 05 章的成绩数据存成 scores.json,再读回来算平均分。
  3. 生成一个 table.csv(姓名/语文/数学),包含 3 行数据,用 Excel 打开不乱码。
  4. 统计一个 .txt 文件的行数、字符数、单词数(类似 Linux 的 wc)。

本章关键词 ​

print(sep/end)、f-string 格式化、open + with、读写模式、encoding="utf-8"、json.dump/load、csv、pathlib

试图用自己的方式,重新定义属于我的人生