我改了一下你的程式碼,實測是可以從 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()
我改了一下你的程式碼,實測是可以從 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()