我正在尝试解析从互联网上提取的 csv 文件。 python 中的 csv 阅读器将每个字符分成一个列表元素。
r.text是格式正确的csv文件
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)
如何正确解析这个文件?谢谢!
最佳答案
您将多行字符串传递给 csv 模块:它被视为 1 个字符行的列表。
您必须使用 str.splitlines()
按行拆分,如下所示:
csv_f = csv.reader(r.text.splitlines(), skipinitialspace=True, delimiter=',')
for row in csv_f:
print (row)
结果:
['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']
...
关于python - 我正在尝试解析从互联网上提取的 csv 文件。 python 中的 csv 阅读器将每个字符分成一个列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40313278/