Skip to content

Instantly share code, notes, and snippets.

@Lazhari
Created June 28, 2016 14:15
Show Gist options
  • Save Lazhari/4ca45d52478ea979703940075c895baf to your computer and use it in GitHub Desktop.
Save Lazhari/4ca45d52478ea979703940075c895baf to your computer and use it in GitHub Desktop.
Reading CSV file -- Python
import os
DATADIR = ""
DATAFILE = "beatles-diskography.csv"
SEPARATOR = ","
def parse_file(datafile):
data = []
header= []
with open(datafile, "rb") as f:
for i, line in enumerate(f):
line = line.replace('\n', '')
if i==0:
header = line.split(SEPARATOR)
else:
row = dict(zip(header, line.split(SEPARATOR)))
data.append(row)
return data
def test():
# a simple test of your implemetation
datafile = os.path.join(DATADIR, DATAFILE)
d = parse_file(datafile)
firstline = {'Title': 'Please Please Me', 'UK Chart Position': '1', 'Label': 'Parlophone(UK)', 'Released': '22 March 1963', 'US Chart Position': '-', 'RIAA Certification': 'Platinum', 'BPI Certification': 'Gold'}
tenthline = {'Title': '', 'UK Chart Position': '1', 'Label': 'Parlophone(UK)', 'Released': '10 July 1964', 'US Chart Position': '-', 'RIAA Certification': '', 'BPI Certification': 'Gold'}
assert d[0] == firstline
assert d[9] == tenthline
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment