Python怎么把循环得到的结果按照列依次写入到一个csv文件中
1个回答
展开全部
我改了一下你的代码,实测是可以从 a.csv复制到 b.csv中
import csv
def foo():
with open('a.csv', 'r') as f:
reader = csv.DictReader(f)
rows = [row for row in reader]
if not rows:
return
with open('b.csv', mode='w', newline='', errors='ignore') as f2:
for index, row in enumerate(rows):
if index == 0:
f_csv = csv.DictWriter(f2, fieldnames=list(row.keys()))
f_csv.writeheader()
f_csv.writerow(row)
if __name__ == '__main__':
foo()
import csv
def foo():
with open('a.csv', 'r') as f:
reader = csv.DictReader(f)
rows = [row for row in reader]
if not rows:
return
with open('b.csv', mode='w', newline='', errors='ignore') as f2:
for index, row in enumerate(rows):
if index == 0:
f_csv = csv.DictWriter(f2, fieldnames=list(row.keys()))
f_csv.writeheader()
f_csv.writerow(row)
if __name__ == '__main__':
foo()
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询