前端 Python 3.12

7. 输入与输出

f-string 与 format、str/repr、文件的 with 与编码、JSON 序列化——脚本输出与持久化数据的常用拼图。

7.1 输出格式化

f-string(首选)

import math

name, age = "Alice", 25
print(f"{name} is {age}")       # Alice is 25
print(f"π ≈ {math.pi:.3f}")     # π ≈ 3.142

table = {"Sjoerd": 4127, "Jack": 4098, "Dcab": 7678}
for name, phone in table.items():
    print(f"{name:10}{phone:10d}")
# 每次迭代一行,共三行:
# Sjoerd     →       4127
# Jack       →       4098
# Dcab       →       7678

print(f"{name=!s}")  # name='Dcab'(循环结束后 name 为最后一项的键;自解释调试输出)

str.format(维护旧代码仍会看到)

print("{} + {} = {}".format(1, 2, 3))  # 1 + 2 = 3
print("{name}: {score}".format(name="Tom", score=99))  # Tom: 99

user = {"id": 100, "name": "Amy"}
print("{id}{name}".format(**user))  # 100 → Amy

手动对齐与补零

for x in range(1, 6):
    print(repr(x).rjust(2), repr(x * x).rjust(3), repr(x**3).rjust(4))
# 共 5 行,例如:
# ' 1' '  1'    '   1'
# ' 2' '  4'    '   8'
# ' 3' '  9'    '  27'
# ' 4' ' 16'    '  64'
# ' 5' ' 25'    ' 125'

print("12".zfill(5))  # 00012(打印无引号;值为补零后的字符串)

旧式 %(了解即可)

import math

print("pi = %.3f" % math.pi)  # pi = 3.142

str() vs repr()

s = "hello\nworld"
print(str(s))   # hello(换行)world;人读友好
print(repr(s))  # 'hello\nworld';解释器倾向可复现的形式

7.2 文件读写

总原则:文本显式 encoding="utf-8";用 with 关文件。Windows 上缺 encoding 有时会踩 GBK 默认坑。

from pathlib import Path

text_path = Path("test.txt")
text_path.write_text("hello\n", encoding="utf-8")

print(text_path.read_text(encoding="utf-8"))  # hello(末尾换行)

等价 open 写法(需要逐块读或 seek 时更常用):

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

with open("out.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("one more line\n")

逐行读(省内存)

with open("big.log", encoding="utf-8") as f:
    for line in f:
        line = line.rstrip("\n")
        if line:
            ...  # 在这里处理一行(解析、聚合、写下游)

二进制模式

png_path = Path("logo.png")
data = png_path.read_bytes()
assert data[:8] == b"\x89PNG\r\n\x1a\n"  # 魔数检查示例

7.3 JSON

  • 适合跨语言datetime不原生支持,要自己转字符串或用自定义 default
  • 绝不要pickle 处理不可信输入(等效执行代码级别风险)。
import json
from datetime import date

payload = {"ok": True, "when": date.today().isoformat()}

print(json.dumps(payload, ensure_ascii=False))  # {"ok": true, "when": "YYYY-MM-DD"}(日期随运行日变化)

raw = '{"nums": [1, 2, 3]}'
obj = json.loads(raw)
print(sum(obj["nums"]))  # 6

# 落地文件:indent 让 diff 可读
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(payload, f, ensure_ascii=False, indent=2)

7.4 速记

任务选什么
结构化日志 / 调试f-string
大文件行遍历for line in f
路径与一小块 APIpathlib.Path
跨语言持久化JSON(必要时自定义编码)

权威延伸7. Input and Output

On this page