直接将CSV下载到Python CSV解析器中

时间:2011-10-02 07:17:13

标签: python parsing csv

我正在尝试从morningstar下载CSV内容,然后解析其内容。如果我将HTTP内容直接注入Python的CSV解析器,结果格式不正确。但是,如果我将HTTP内容保存到文件(/tmp/tmp.csv),然后在python的csv解析器中导入文件,结果是正确的。换句话说,为什么:

def finDownload(code,report):
    h = httplib2.Http('.cache')
    url = 'http://financials.morningstar.com/ajax/ReportProcess4CSV.html?t=' + code + '&region=AUS&culture=en_us&reportType='+ report + '&period=12&dataType=A&order=asc&columnYear=5&rounding=1&view=raw&productCode=usa&denominatorView=raw&number=1'
    headers, data = h.request(url)
    return data

balancesheet = csv.reader(finDownload('FGE','is'))
for row in balancesheet:
    print row

返回:

['F']
['o']
['r']
['g']
['e']
[' ']
['G']
['r']
['o']
['u']
     (etc...)

而不是:

[Forge Group Limited (FGE) Income Statement']

1 个答案:

答案 0 :(得分:9)

问题是由于文件的迭代是逐行完成的,而字符串的迭代是逐个字符完成的。

你想要StringIO / cStringIO(Python 2)或io.StringIO(Python 3,感谢John Machin指点我)所以字符串可以被视为文件 - 喜欢对象:

Python 2:

mystring = 'a,"b\nb",c\n1,2,3'
import cStringIO
csvio = cStringIO.StringIO(mystring)
mycsv = csv.reader(csvio)

Python 3

mystring = 'a,"b\nb",c\n1,2,3'
import io
csvio = io.StringIO(mystring, newline="")
mycsv = csv.reader(csvio)

两者都会在引用字段中正确保留换行符:

>>> for row in mycsv: print(row)
...
['a', 'b\nb', 'c']
['1', '2', '3']