[Tutor] Reading a CSV file

David Rock david at graniteweb.com
Fri Jun 12 18:42:57 EDT 2020


* John Weller <john at johnweller.co.uk> [2020-06-12 18:59]:
> I have a CSV file with 366 rows each with 4 comma separated fields; day_no,
> date, sunrise, sunset.  The top row contains the field names.  I want access
> the time of sunrise and sunset from file for a particular day_no.
> 
>  
> 
> I have tried:
> 
>  
> 
> import csv
> 
> with open('sun_times_gmt.csv', newline= '') as csvfile:
>     sun_times = csv.DictReader(csvfile, delimiter=',')
>     for row in sun_times:
>         print(row['sunrise'])
> 
> 
> but it prints out the entire column.  How do I specify a particular row?

This is because you are telling it to print every row.  You need to add
an if statement that prints only if day_no matches the entry you want.
For example:

with open('sun_times_gmt.csv', newline= '') as csvfile:
    sun_times = csv.DictReader(csvfile, delimiter=',')
    for row in sun_times:
        if row['day_no'] == 'your day_no value here':
            print(row['sunrise'])


You could also play around with using the value of day_no to be a key
for the data so you can access it more directly.  If day_no is unique,
you can do this:

days = {}
with open('sun_times_gmt.csv', newline= '') as csvfile:
    sun_times = csv.DictReader(csvfile, delimiter=',')
    for row in sun_times:
        days[row['day_no']] = row

print(days['your day_no value here']['sunrise'])


It depends on exactly how you want to reference the data later

-- 
David Rock
david at graniteweb.com


More information about the Tutor mailing list