python循环写入数据到.csv文件中

1. 创建文件夹和写入表头

    os.makedirs(os.path.join('..', 'data'), exist_ok=True)  # 创建数据文件夹
    data_file = os.path.join('..', 'data', 'loss.csv')
    with open(data_file, 'w', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['epoch', 'batch_index', 'loss'])

2. 追加数据

            with open(data_file, 'a', encoding='utf-8', newline='') as f:
                writer = csv.writer(f)
                writer.writerow([e, batch_index, loss.item()])

注意: 如果需要覆盖数据,使用w,即:

 with open(data_file, 'w', encoding='utf-8', newline='') as f:

如果是追加数据在后面,使用a:

 with open(data_file, 'a', encoding='utf-8', newline='') as f:

其中 newline=‘’,表示换行


版权声明:本文为qq_41915623原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。