简体   繁体   中英

Hiding Columns in CSV files in Python

The goal of this source code is to only print the country population and country name. I'm fairly new to Python and working with CSV's and databases, but I was told in a code review storing the data in a CSV would work better.

Solved: There is another problem as well. When asking for a country, it doesn't matter whether you put in a correct or wrong country, it still counts it as it not being in the list.

Source Code:

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 File:

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 

It's because you are using an space as delimiter but your csv file is using commas as delimiters.

Change

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

to

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

Anyway, I think you are using the wrong data structure, if you read your CSV file to a dictionary then you can access country names and population easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM