写入
# 写入文本内容
with open('test.txt','w',encoding='utf-8') as file:
file.write('要写入的字符串')
# 新增追加文本内容
with open('test.txt','a') as file:
file.write('新增写入内容')
# 二进制写入
with open('test.jpg','wb') as file:
file.write('例二进制图片')
读取
# 读取文本内容
with open('test.txt','r') as file:
file.read()
# 二进制读取
with open('test.txt','rb') as file:
file.read()
CSV的读取与写入
import csv
# 写入新的CSV文件
with open('test.csv','w',newline='') as file: # 中间不换行
writer=csv.writer(file) #准备写入文件
writer.writerow(['内容1','内容2']) # 列表写入第一行
writer.writerow(['内容1','内容2']) # 列表写入第二行
....
# 新增追加CSV内容
with open('test.csv','a') as file:
writer=csv.writer(file) # 准备写入文件
writer.writerow(['内容1','内容2']) # 下面增加一行
# 读取csv文件内容
with open('test.csv','r') as file:
reader=csv.reader(file)
for i in reader:
print(i)