cwalsh8600 cwalsh8600 - 1 month ago 8
Python Question

I am trying to parse a csv file I am pulling from the internet. The csv reader in python is separating each character into a list element

r.text is a csv file that is properly formatted correctly

r = requests.get('http://chart.finance.yahoo.com/table.csv?s=USLV&a=0&b=1&c=2012&d=8&e=30&f=2016&g=m&ignore=.csv')

csv_f = csv.reader(r.text, skipinitialspace=True, delimiter=',')
for row in csv_f:
print (row)

Answer

You're passing a multi-line string to the csv module: it is seen as a list of 1-character lines.

You have to split according to the lines using str.splitlines() as follows:

csv_f = csv.reader(r.text.splitlines(), skipinitialspace=True, delimiter=',')
for row in csv_f:
    print (row)

result:

['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
['2016-09-01', '20.66', '25.790001', '20.48', '21.98', '1302000', '21.98']
['2016-08-01', '27.969999', '29.09', '20.00', '20.60', '1314100', '20.60']
['2016-07-01', '23.73', '28.049999', '23.48', '27.49', '2247200', '27.49']
['2016-06-01', '13.74', '22.200001', '13.36', '22.110001', '1536800', '22.110001']
['2016-05-02', '19.370001', '19.379999', '13.70', '13.75', '1015600', '13.75']
...