【学Python自动化】 7. Python 输入与输出学习笔记
一、更复杂的输出格式
三种输出方式
-
表达式语句:直接写变量或表达式
-
print() 函数:最常用的输出方式
-
文件对象的 write() 方法:输出到文件
1 格式化字符串字面值 (f-strings) - 推荐使用
# 基本用法
year = 2016
event = 'Referendum'
print(f'Results of the {year} {event}') # Results of the 2016 Referendum# 格式控制
import math
print(f'Pi is approximately {math.pi:.3f}') # Pi is approximately 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# 转换修饰符
animals = 'eels'
print(f'My hovercraft is full of {animals!r}') # My hovercraft is full of 'eels'# 调试用法 (Python 3.8+)
bugs = 'roaches'
count = 13
print(f'{bugs=} {count=}') # bugs='roaches' count=13
2 字符串 format() 方法
# 位置参数
print('{0} and {1}'.format('spam', 'eggs')) # spam and eggs
print('{1} and {0}'.format('spam', 'eggs')) # eggs and spam# 关键字参数
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))# 混合使用
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))# 数字格式化
yes_votes = 42_572_654
total_votes = 85_705_149
percentage = yes_votes / total_votes
print('{:-9} YES votes {:2.2%}'.format(yes_votes, percentage))
# 42572654 YES votes 49.67%# 表格格式化
for x in range(1, 11):print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
3 手动格式化字符串
# 字符串对齐方法
print('12'.rjust(5)) # ' 12' - 右对齐
print('12'.ljust(5)) # '12 ' - 左对齐
print('12'.center(5)) # ' 12 ' - 居中
print('12'.zfill(5)) # '00012' - 填充零# 手动创建表格
for x in range(1, 11):print(repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4))
4 旧式字符串格式化 (% 操作符)
# 基本用法
import math
print('The value of pi is approximately %5.3f.' % math.pi)# 多个值
name = 'John'
age = 25
print('Name: %s, Age: %d' % (name, age))
str() vs repr()
s = 'Hello, world.'
print(str(s)) # Hello, world. - 给人阅读
print(repr(s)) # 'Hello, world.' - 给解释器阅读hello = 'hello, world\n'
print(repr(hello)) # 'hello, world\n' - 显示转义字符
二、读写文件
文件打开模式
模式 | 描述 | 说明 |
---|---|---|
‘r’ | 读取(默认) | 文件必须存在 |
‘w’ | 写入 | 创建新文件或覆盖现有文件 |
‘a’ | 追加 | 在文件末尾添加内容 |
‘r+’ | 读写 | 文件必须存在 |
‘b’ | 二进制模式 | 与上述模式组合使用 |
推荐的文件操作方式
# 使用 with 语句自动关闭文件
with open('workfile', 'r', encoding='utf-8') as f:read_data = f.read()
print(f.closed) # True - 文件已自动关闭# 读取文件内容的不同方式
with open('file.txt', 'r') as f:content = f.read() # 读取整个文件line = f.readline() # 读取一行lines = f.readlines() # 读取所有行到列表# 逐行读取(内存高效)
with open('file.txt', 'r') as f:for line in f:print(line, end='') # 逐行处理
文件写入操作
# 文本写入
with open('output.txt', 'w', encoding='utf-8') as f:f.write('Hello, world!\n')f.write('Second line\n')# 写入其他类型需要先转换
values = ('the answer', 42)
with open('data.txt', 'w') as f:f.write(str(values)) # 转换为字符串
文件定位
# 二进制模式下的文件定位
with open('workfile', 'rb+') as f:f.write(b'0123456789abcdef')f.seek(5) # 移动到第6个字节print(f.read(1)) # b'5'f.seek(-3, 2) # 移动到倒数第3个字节print(f.read(1)) # b'd'
2 使用 json 保存结构化数据
JSON 基本操作
import json# Python 对象 → JSON 字符串
x = [1, 'simple', 'list']
json_string = json.dumps(x) # '[1, "simple", "list"]'# JSON 字符串 → Python 对象
x = json.loads(json_string) # [1, 'simple', 'list']# 文件操作
data = {'name': 'John', 'age': 30, 'cities': ['New York', 'Paris']}# 写入文件
with open('data.json', 'w', encoding='utf-8') as f:json.dump(data, f)# 从文件读取
with open('data.json', 'r', encoding='utf-8') as f:loaded_data = json.load(f)
JSON 与 Python 类型对应
JSON 类型 | Python 类型 |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
三、⚡ 重要注意事项
文件操作最佳实践
-
总是使用 with 语句:确保文件正确关闭
-
指定编码:特别是文本文件,推荐 encoding=‘utf-8’
-
二进制文件用 ‘b’ 模式:如图片、视频等
-
大文件逐行处理:避免内存不足
格式化选择建议
-
现代代码:使用 f-strings(最简洁)
-
兼容旧版本:使用 str.format()
-
避免使用:% 操作符(旧式)
JSON 使用场景
-
配置文件:程序设置和配置
-
数据交换:API 通信和数据传输
-
数据持久化:简单数据结构存储
四、💡 实用技巧
上下文管理器多个文件
# 同时处理多个文件
with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:for line in infile:outfile.write(line.upper())
JSON 美化输出
data = {'name': 'John', 'age': 30, 'cities': ['New York', 'Paris']}
pretty_json = json.dumps(data, indent=4, ensure_ascii=False)
# {
# "name": "John",
# "age": 30,
# "cities": [
# "New York",
# "Paris"
# ]
# }
文件存在检查
import osif os.path.exists('file.txt'):with open('file.txt', 'r') as f:content = f.read()
else:print("文件不存在")
这个笔记涵盖了 Python 输入输出的核心概念,从简单的打印到复杂的文件操作和数据序列化!