Reputation: 149
I am trying to read a CSV file for processing in Python. All I want is to associate the values of cities to a state in a dictionary which is present in the CSV all comma separated. After getting the name of state I want to get the cities as its values for which I want to know the end of line of the file.
My structure of CSV is like :
State,city1,city2,city3,city4,city5,..,cityn
Since all the states may not have values for all the cities, some city values are empty.
Upvotes: 0
Views: 362
Reputation: 23088
Basically, two solutions to break your content on each new line:
with open(your_file) as f:
for line in f:
do_stuff()
or
for line in you_csv_content.split("\n"):
do_stuff()
Upvotes: 1
Reputation: 174672
If you iterate over the file, it will automatically yield each line; in other words you don't need to know where the line ends:
from collections import defaultdict
d = defaultdict(list)
with open('somefile.csv') as f:
for line in f: # this will automatically step over each line correctly
bits = line.split(',')
d[bits[0]] += bits[1:]
for state,cities in d.items():
print('{} has {} cities: '.format(state, len(cities))
for city in cities:
print('\t{}'.format(city))
Upvotes: 3