[Tutor] Reading a CSV file
John Weller
john at johnweller.co.uk
Sat Jun 13 10:59:23 EDT 2020
Many thanks to all who replied. I hoped it would be something like a
dictionary. The docs say that a dictionary is a sequence of key pairs -
key:value but it appears that the value can be several fields. Is this the
case?
This program is intended to run 24/7 getting data every 10 minutes and using
it to control equipment dependent on whether it is day or night. There will
be a setup function and a loop function. I assume I can put the first part
to create the dictionary is setup and the call in the loop?
Thanks again
John
John Weller
01380 723235
07976 393631
-----Original Message-----
From: Tutor <tutor-bounces+john=johnweller.co.uk at python.org> On Behalf Of
David Rock
Sent: 12 June 2020 23:43
To: tutor at python.org
Subject: Re: [Tutor] Reading a CSV file
* 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
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list