Python は csv ファイルを作成し、データを追加し、データの空白行を残さない

 csv ファイルを作成し、データを追加する前に csv ファイルが存在するかどうかを確認します

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])

データを追加します。 open() で'a+' モードで開くことに注意してください。 

データの空白行を残さないでください。パラメータ newline='' を指定してください

おすすめ

転載: blog.csdn.net/weixin_46159962/article/details/128207731