将 CSV 直接下载到 Python 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 + '®ion=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']
?
I'm trying to download CSV content from morningstar and then parse its contents. If I inject the HTTP content directly into Python's CSV parser, the result is not formatted correctly. Yet, if I save the HTTP content to a file (/tmp/tmp.csv), and then import the file in the python's csv parser the result is correct. In other words, why does:
def finDownload(code,report):
h = httplib2.Http('.cache')
url = 'http://financials.morningstar.com/ajax/ReportProcess4CSV.html?t=' + code + '®ion=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
return:
['F']
['o']
['r']
['g']
['e']
[' ']
['G']
['r']
['o']
['u']
(etc...)
instead of:
[Forge Group Limited (FGE) Income Statement']
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该问题是由于文件的迭代是逐行完成的,而字符串的迭代是逐字符完成的。
您需要
StringIO
/cStringIO
(Python 2) 或io.StringIO
(Python 3,感谢 John Machin 向我指出),因此字符串可以被视为类似文件的对象:Python 2:
Python 3:
两者都会正确保留带引号的字段内的换行符:
The problem results from the fact that iteration over a file is done line-by-line whereas iteration over a string is done character-by-character.
You want
StringIO
/cStringIO
(Python 2) orio.StringIO
(Python 3, thanks to John Machin for pointing me to it) so a string can be treated as a file-like object:Python 2:
Python 3:
Both will correctly preserve newlines inside quoted fields: