Create a csv file, and determine whether the csv file exists before appending data
example
import csv
import os
csv_header = ['time', 'temp', 'gas']
file_name = 'model_data.csv'
if not os.path.exists(file_name): #文件不存在
with open(file_name, 'w', encoding='utf8', newline='') as file:
writer = csv.writer(file)
writer.writerow(csv_header)
with open(file_name, 'a+', encoding='utf8', newline='') as file:
writer = csv.writer(file)
writer.writerow([1, 10, 20])
writer.writerow([2, 11, 20])
Append data, pay attention to open with 'a+' mode in open() .
Do not leave a blank line of data, specify the parameter newline=''