[Tutor] Reading a CSV file
Cameron Simpson
cs at cskk.id.au
Fri Jun 12 18:46:38 EDT 2020
On 12Jun2020 18:59, John Weller <john at johnweller.co.uk> wrote:
>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?
By putting the print inside an if-statement that recognises the row. So
changing:
for row in sun_times:
print(row['sunrise'])
into:
for row in sun_times:
if some test of row['day_no']:
print(row['sunrise'])
which will cause the print statement to only work if the test succeeds.
What the test is depends on what "a particular day_no" means.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list