模式切换
文件与 I/O
文件操作
打开和关闭文件
在进行文件操作时,首先要打开文件,操作完成后要关闭文件。Python 提供了内置的 open() 函数来打开文件。
open()函数: 用于打开文件,并返回文件对象。pythonfile = open('filename', 'mode')filename:文件的路径或名称。mode:文件的操作模式,如只读、写入、追加等。
常用的文件操作模式:
'r':只读模式,文件必须存在。'w':写入模式,文件不存在时创建,存在时清空内容。'a':追加模式,文件不存在时创建,存在时内容添加到末尾。'b':以二进制模式打开文件,结合'rb','wb'等模式使用。
关闭文件
使用完文件后,应该调用 close() 方法关闭文件,释放资源:
python
file.close()使用 with 语句
with 语句会自动处理文件关闭问题,是处理文件的推荐方式:
python
with open('example.txt', 'r')as file:
content = file.read()
print(content)
# 文件在with语句块结束后自动关闭文件的读写操作
读文件
read():读取文件的全部内容。readline():每次读取文件的一行。readlines():读取所有行并返回一个列表。
python
# 读取文本文件的内容
with open('example.txt', 'r')as file:
content = file.read() # 读取整个文件
print(content)
# 按行读取文件
with open('example.txt', 'r')as file:
for line in file:
print(line.strip()) # 去除每行末尾的换行符写文件
write():将字符串写入文件。writelines():将一个字符串列表写入文件。
python
# 写入文件
with open('output.txt', 'w')as file:
file.write("Hello, world!\n")
file.write("This is a new line.")
# 写入多个行
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w')as file:
file.writelines(lines)二进制文件的读写
- 以 二进制模式(
'rb','wb')读写文件时,数据是以字节形式读写的。
python
# 读取二进制文件(如图片、音频)
with open('image.jpg', 'rb')as file:
binary_data = file.read()
# 写入二进制文件
with open('copy.jpg', 'wb')as file:
file.write(binary_data)文件指针与操作模式
文件指针指向文件的当前位置,所有的读写操作都从当前指针位置开始。
seek(offset, whence):移动文件指针到指定位置。offset:偏移量。whence:起始位置(0代表文件开头,1代表当前位置,2代表文件末尾)。
python
# 移动指针到文件开头
with open('example.txt', 'r')as file:
file.seek(0)
first_char = file.read(1) # 读取第一个字符
print(first_char)tell():返回文件指针的当前位置。
python
with open('example.txt', 'r')as file:
file.read(5)
position = file.tell() # 返回当前位置
print(f"Current file pointer position: {position}")序列化与反序列化
序列化是指将对象转换为字节流或字符串,以便保存到文件或传输;反序列化则是将字节流或字符串还原为对象。Python 支持通过 pickle 和 json 模块进行序列化与反序列化。
pickle 模块
pickle 模块用于将任意 Python 对象序列化为二进制格式,或将其反序列化为 Python 对象。它常用于将对象保存到文件或从文件中加载对象。
pickle.dump():将Python对象序列化并写入文件。pickle.load():从文件中读取序列化的数据并将其反序列化为Python对象。
python
import pickle
# 序列化对象并写入文件
data = {'name': 'Alice', 'age': 25, 'city': 'New York'}
with open('data.pkl', 'wb')as file:
pickle.dump(data, file)
# 从文件中读取并反序列化对象
with open('data.pkl', 'rb')as file:
loaded_data = pickle.load(file)
print(loaded_data)输出:
{'name': 'Alice', 'age': 25, 'city': 'New York'}json 模块
json 模块用于处理 JSON 格式的数据,JSON 是一种轻量级的数据交换格式,常用于Web开发中。与 pickle 不同,json 仅支持基本数据类型(如字典、列表、字符串、整数等)的序列化。
json.dump():将 Python 对象序列化为 JSON 格式并写入文件。json.load():从文件中读取 JSON 数据并反序列化为 Python 对象。json.dumps():将 Python 对象序列化为 JSON 格式的字符串。json.loads():将 JSON 字符串反序列化为 Python 对象。
python
import json
# 序列化对象并写入文件
data = {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}
with open('data.json', 'w')as file:
json.dump(data, file)
# 从文件中读取并反序列化对象
with open('data.json', 'r')as file:
loaded_data = json.load(file)
print(loaded_data)输出:
{'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}python
# JSON字符串的序列化与反序列化
json_str = json.dumps(data)
print(json_str) # 输出为JSON格式字符串
# 将JSON字符串反序列化为Python对象
python_data = json.loads(json_str)
print(python_data)总结
- 文件操作:
open()函数用于打开文件,文件操作模式包括读取、写入、追加等;with语句是处理文件的推荐方式。 - 文件指针:使用
seek()和tell()来操作和获取文件指针位置。 - 序列化与反序列化:
pickle用于处理 Python 的任意对象,json则用于处理 JSON 格式的数据,适合 Web 应用。
