在這些行中讀取 CSV 文件時:csv_file = open(sys.argv[1], "r") # reading the csv file into memorycsv_reader = csv.DictReader(csv_file)當我嘗試在使用 for 循環時制作 csv_reader 的副本時它起作用了,但是對該副本版本的任何更改都會影響 csv_reader 變量,加上for line in csv_reader: copy = line breakfor line in csv_reader: print(line)第二個 for 循環將打印除 thencsv_file 中第一行以外的所有內容,為什么?
1 回答

慕桂英546537
TA貢獻1848條經驗 獲得超10個贊
您可以csv_file.seek(0)在 for 循環之間使用。
csv_file = open(sys.argv[1], "r")
csv_reader = csv.DictReader(csv_file)
for line in csv_reader:
copy = line
break
csv_file.seek(0)
for line in csv_reader:
print(line)
# Outputs full csv file
添加回答
舉報
0/150
提交
取消