如何告诉 for 循环从头开始读取文件?
how to tell the for loop to read a file from the start?
在这些行中读取 CSV 文件时:
csv_file = open(sys.argv[1], "r") # reading the csv file into memory
csv_reader = csv.DictReader(csv_file)
当我尝试使用 for 循环复制 csv_reader 时它起作用了,但是对该副本版本的任何更改都会影响 csv_reader 变量,加上
for line in csv_reader:
copy = line
break
for line in csv_reader:
print(line)
第二个 for 循环将打印除 thencsv_file 中第一行以外的所有内容,为什么?
您可以在 for 循环之间使用 csv_file.seek(0)
。
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
在这些行中读取 CSV 文件时:
csv_file = open(sys.argv[1], "r") # reading the csv file into memory
csv_reader = csv.DictReader(csv_file)
当我尝试使用 for 循环复制 csv_reader 时它起作用了,但是对该副本版本的任何更改都会影响 csv_reader 变量,加上
for line in csv_reader:
copy = line
break
for line in csv_reader:
print(line)
第二个 for 循环将打印除 thencsv_file 中第一行以外的所有内容,为什么?
您可以在 for 循环之间使用 csv_file.seek(0)
。
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