CSV读写
初始化
import csv
import os
filename = 'example.csv'
# 检查文件是否存在
if not os.path.isfile(filename):
# 如果文件不存在,则创建一个空的CSV文件
with open(filename, 'w', newline='',encoding='utf-8') as file:
writer = csv.writer(file)
#创建列标题
writer.writerow(['Header1', 'Header2', 'Header3'])
读行
with open(filename, 'r', newline='') as file:
reader = csv.reader(file)
for row in reader:
print(row)
写行
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Value1', 'Value2', 'Value3'])
#file.flush() #强制保存,一般python在结束时会自动存储不用这个命令