返回 1. 使用
3. 使用
4. 使用
5. 使用
Python文件读写指南:从零基础到进阶,一文掌握!
后端
2024-01-18 07:10:29
Python文件读写基础
1. 打开文件
# 以只读方式打开文件
file = open('test.txt', 'r')
# 以写的方式打开文件
file = open('test.txt', 'w')
# 以追加的方式打开文件
file = open('test.txt', 'a')
2. 读取文件
# 读取文件内容并保存到变量中
data = file.read()
# 读取文件内容并逐行保存到列表中
data = file.readlines()
3. 写入文件
# 向文件写入内容
file.write('Hello, world!')
# 向文件追加内容
file.writelines(['Line 1', 'Line 2', 'Line 3'])
4. 关闭文件
# 关闭文件
file.close()
Python文件读写进阶
1. 使用with
语句打开文件
# 使用with语句打开文件,可以自动关闭文件
with open('test.txt', 'r') as file:
data = file.read()
2. 使用二进制模式打开文件
# 以二进制模式打开文件,可以读取和写入二进制数据
with open('image.png', 'rb') as file:
data = file.read()
3. 使用csv
模块处理CSV文件
import csv
# 读取CSV文件
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# 写入CSV文件
with open('data.csv', 'w') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['John', '30', 'New York'])
4. 使用json
模块处理JSON文件
import json
# 读取JSON文件
with open('data.json', 'r') as file:
data = json.load(file)
# 写入JSON文件
with open('data.json', 'w') as file:
json.dump(data, file, indent=4)
5. 使用pickle
模块处理序列化对象
import pickle
# 序列化对象
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.pickle', 'wb') as file:
pickle.dump(data, file)
# 反序列化对象
with open('data.pickle', 'rb') as file:
data = pickle.load(file)
结语
Python文件读写是Python编程中必不可少的技能,无论你是初学者还是进阶学习者,掌握文件读写对于你的编程实践都大有裨益。希望这份指南能够帮助你快速入门Python文件读写,并在实践中灵活运用这些知识。