csv 为什么这本字典突然变空了?

6ojccjat  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(120)

我有一个CSV文件“country.csv”,它看起来像这样:

Country Code,Country Name,Country-ID
US,United States,0
DE,Germany,1
AU,Australia,2
CZ,Czechia,3
CA,Canada,4
AR,Argentina,5
BR,Brazil,6
PT,Portugal,7
GB,United Kingdom,8
IT,Italy,9
GG,Guernsey,10
RO,Romania,11
ES,Spain,12
FR,France,13
NL,Netherlands,14
,,15
SK,Slovakia,16

我编写了一个简单的Python脚本,使用字典将这个文件读入“country_dictionary”并打印出“行”。然而,在跑过“country_dictionary”一次后,它突然变得空荡荡的。你能告诉我我做错了什么吗?

import csv

def csv_to_dictionary(csv_name, delimiter):
    input_file = csv.DictReader(open(csv_name, 'r', encoding='utf-8'), delimiter=delimiter)
    return input_file

country_dictionary = csv_to_dictionary("country.csv", ',')
country_list = []
for row in country_dictionary:
    print(row)
    country_list.append(row["Country Code"])
print(country_list)                                   #Up to here everything works as intended

for row in country_dictionary:
    print(row)                        # The dictionary seems to be empty?
nbysray5

nbysray51#

您的脚本将读取整个文件,因此在第二个for循环中没有其他内容可读取。如果您想再次通读,请再次在循环前添加country_dictionary = csv_to_dictionary("country.csv", ',')
或者像@Pujianto提到的,让csv_to_dictionary返回一个带有return [ row for row in input_file ]input_file的副本

相关问题