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

文章目录

    • 1. 创建文件夹和写入表头
    • 2. 追加数据

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=‘’,表示换行

你可能感兴趣的:(python,python,开发语言)