我有以下脚本可写入 .csv 文件-可以,但是我正在多个文件上运行该脚本。
我正在使用:from csv import DictWriter
当前它只是一次又一次地写和更新同一行。所以我的/ metrics.csv
只能得到一行...我如何才能将其更新为每次都有新行吗?
/find_pending_records.py
def get_excel_data(self):
"""Places excel data into pandas dataframe"""
...........
with open("./logs/metrics.csv", "w", newline="") as f:
csv_writer = DictWriter(f, ['date', 'total', 'processed', 'skipped', 'total_zips', 'success_rate'])
csv_writer.writeheader()
currentDT = datetime.datetime.now()
success_rate = num_valid_records / total_records * 100
csv_writer.writerow(dict(date=currentDT,
total=total_records,
processed=num_valid_records,
skipped=num_invalid_records,
success_rate=num_valid_records / total_records * 100))
return self.clean_data_frame(excel_data)
答案 0 :(得分:3)
即使没有深入到您的代码中,问题仍在下一行
with open("./logs/metrics.csv", "w", newline="") as f:
这将以write
模式打开文件,因此您需要将w
更改为a
,以便改为以append
模式打开文件。