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

慕桂英546537
TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以csv_file.seek(0)在 for 循環(huán)之間使用。
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
添加回答
舉報(bào)
0/150
提交
取消