Fairly new to python, forgive me if this is a basic question about learning how to use CSV files.
import csv
theReader = csv.reader(open('filename.csv'), delimiter=',')
for line in theReader:
print line
So I've managed to open the file and can print it sprawling across my screen. But I'm trying to capture the data into Dictionaries.
This is example CSV:
Name,Age,Goals,Passes,Fouls
Ted,21,1,20,1
Ben,28,5,14,4
I now need to create one dictionary with the headings in as the dictionary key (ideally skipping 'name'), then the dictionary values to be filled with the stats.
I'm then going to create another dictionary that has names:dates (dates I'm adding manually) as the key:value
Am I even right to be using the CSV mondule or should I be doing this via standar file type, and splitting lines by the comma?
Python has a built-in library that handles reading your lines as dictionaries for you.
It is DictReader
instead of reader
.
http://docs.python.org/release/3.1.3/library/csv.html#csv.DictReader
Using this, each line would be a dictionary instead of a list.
from csv import DictReader
the_reader = DictReader(open('filename.csv', 'r'))
for line_dict in the_reader:
print(line_dict)
# {'Name': 'Ted', 'Age': '21', 'Goals': '1', 'Passes': '20', 'Fouls': '1'}
In Python 2, the mode is 'rb'
.
the_reader = DictReader(open('filename.csv', 'rb'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With