Skip to content

Instantly share code, notes, and snippets.

@kartoch
Last active November 24, 2017 09:28
Show Gist options
  • Save kartoch/0ae36b15443dda8735527846ac550d82 to your computer and use it in GitHub Desktop.
Save kartoch/0ae36b15443dda8735527846ac550d82 to your computer and use it in GitHub Desktop.
Python @ Polytech'Lille - TP1
#!/usr/bin/python
# Goal: write a simple CSV parser for the video-games CSV file and print the
# sum of the global sales for each console
#
# CSV files are text files with each row is a line where cells are separated
# by comma. Because comma can also be used as value in cell, a value cell
# which contains a comma has a double quote at the start and the end of the
# value.
#
# you're lucky that the CSV file is not complicated
# - there is no more than one value with double quotes by line
# - there is the same number of cells by line
# - cell with quotes are correctly left and right stripped of whitespace
CSV_TO_READ = 'video-games.csv'
def escape_quotes(data):
index_start = 0
for i in range(len(data)):
if (len(data[i]) > 0) and \
(data[i][-1] == '\"') and \
not (data[i][0] == '\"'):
return data[:index_start] + \
[ ",".join(data[index_start:i+1]) ] + \
data[i+1:]
elif (len(data[i]) > 0) and \
(data[i][0] == '\"') and \
not (data[i][-1] == '\"'):
index_start = i
return data
if __name__ == '__main__':
f = open(CSV_TO_READ,'r')
first_line = True
results = {}
for l in f:
if first_line:
first_line = False
continue
data = l.split(',')
data = escape_quotes(data)
console,sales = data[1],float(data[9])
if console in results:
results[console] += sales
else:
results[console] = sales
for i in results:
print(i,results[i])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment