在Python中隐藏CSV文件中的列

0 投票
1 回答
1088 浏览
提问于 2025-04-18 06:13

这段源代码的目的是只打印出国家的人口和国家名称。我对Python和处理CSV文件以及数据库还比较陌生,但有人告诉我,在代码评审中说把数据存储在CSV文件里会更好。

解决的问题:还有另一个问题。当你输入一个国家名时,不管你输入的是正确的国家还是错误的国家,它都会把它当作不在列表里。

源代码:

import random
import csv

print '\nCountries to choose from are\n'
country_list = []

with open('countries.csv', 'rb') as csvfile:
    countryreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for idx, country in enumerate(countryreader):
        print ' '.join(country) # everything besides population and country title should be hidden
        if (idx != 0): # Don't append the fist row (column headers)
            country_list.append(country[0])

startcountry = raw_input('\nWhat country would you like to start in? If you can\'t think of one, you can enter random to choose a random country.').title()

if startcountry == 'Random': # random.sample can be used for more than one country later on
    startcountry = random.choice(country_list)

while startcountry not in country_list:
    startcountry = raw_input('We don\'t know that country. Please enter one from the list above. ')

CSV文件:

Country,Population,Type
China,1363560000,Urban
India,1242070000,Rural
United States,317768000,Urban
Indonesia,249866000,Rural
Brazil,201032714,Rural
Pakistan,186015000,Unspecified 
Nigeria,173615000,Unspecified 
Bangladesh,152518015,Unspecified 
Russia,143700000,Rural
Japan,127120000,Urban
Mexico,119713203,Urban
Philippines,99329000,Unspecified 
Vietnam,89708900,Unspecified 
Egypt,86188600,Unspecified 
Germany,80716000,Urban
Iran,77315000,Unspecified 
Turkey,76667864,Unspecified 
Thailand,65926261,Unspecified 
France,65844000,Urban
United Kingdom,63705000,Urban
Italy,59996777,Urban
South Africa,52981991,Unspecified 
South Korea,50219669,Unspecified 
Colombia,47522000,Rural
Spain,46609700,Unspecified 
Ukraine,45410071,Rural
Kenya,44354000,Unspecified 
Argentina,40117096,Rural
Poland,38502396,Rural
Sudan,37964000,Rural
Uganda,35357000,Unspecified 
Canada,35344962,Unspecified 
Iraq,34035000,Unspecified 

1 个回答

1

这是因为你用空格作为分隔符,但你的CSV文件是用逗号作为分隔符的。

countryreader = csv.reader(csvfile, delimiter=' ', quotechar='|')

改成

countryreader = csv.reader(csvfile, delimiter=',', quotechar='|')

不过,我觉得你用的数据结构不太对。如果你把CSV文件读成一个字典,那么你就可以很方便地访问国家名称和人口数据了。

撰写回答