Python: 输入与输出 (I/O)
2025-02-17
Python 程序需要与外界进行通信,包括用户交互、文件读写、网络访问等,这些操作统称为输入和输出(I/O)。本文主要介绍 Python 中的 I/O 操作,包括字符串格式化、文件操作等。
1. 字符串格式化
1.1 字符串插入
# 控制小数位数示例
x = 1/81
print(x) # 0.012345679012345678
print('value: %.2f' % x) # value: 0.01
print('value: %.5f' % x) # value: 0.012351.2 转换说明符
| 说明符 | 含义 |
|---|---|
| d | 整数 |
| o | 八进制值 |
| x | 小写十六进制数 |
| X | 大写十六进制数 |
| e | 小写科学记数法 |
| E | 大写科学记数法 |
| f | 浮点数 |
| s | 字符串 |
| % | %字符 |
1.3 格式字符串
# format() 方法示例
ss = 'My {pet} has {prob}'.format(pet='dog', prob='fleas')
print(ss) # My dog has fleas
# 按位置替换
sss = 'My {0} has {1}'.format('dog', 'fleas')
print(sss) # My dog has fleas
# 格式化浮点数
print('1/18 = {x:.3f}'.format(x=1/18)) # 1/18 = 0.0562. 文件操作
2.1 文本文件处理
# 写入文件
with open('story.txt', 'w') as f:
f.write('Many had a little lamb,\n and then she had some more.\n')
# 读取文件
with open('story.txt', 'r') as f:
content = f.read()
# 追加内容
with open('story.txt', 'a') as f:
f.write('New line\n')2.2 二进制文件处理
# 检查是否为 GIF 文件
def is_gif(fname):
with open(fname, 'br') as f:
first4 = tuple(f.read(4))
return first4 == (0x47, 0x49, 0x46, 0x38)3. 序列化
3.1 pickle 模块
import pickle
def save_data():
grades = {
'alan': [4, 8, 10, 10],
'tom': [7, 7, 7, 8]
}
with open('grades.data', 'wb') as f:
pickle.dump(grades, f)
def load_data():
with open('grades.data', 'rb') as f:
return pickle.load(f)4. 网络操作
4.1 读取网页
import urllib.request
def get_webpage(url):
page = urllib.request.urlopen(url)
return page.read()4.2 浏览器操作
import webbrowser
def open_webpage(url):
return webbrowser.open(url)总结
Python 提供了丰富的 I/O 操作功能:
- 灵活的字符串格式化方法
- 完整的文件操作接口
- 强大的序列化工具
- 便捷的网络访问能力
注意:在处理文件时要注意正确关闭文件,推荐使用 with 语句进行文件操作。