我正在尝试遍历 csv
文件中的行。我从 Web 位置获取 csv
文件作为 string
。当数据存储在文件中时,我知道如何使用 with
创建 csv.reader
。我不知道的是,如何在不将 string
存储到文件的情况下使用 csv.reader
获取行。我正在使用 Python 2.7.12。
我试过像这样创建 StringIO
对象:
from StringIO import StringIO
csv_data = "some_string\nfor_example"
with StringIO(csv_data) as input_file:
csv_reader = reader(csv_data, delimiter=",", quotechar='"')
但是,我收到了这个错误:
Traceback (most recent call last):
File "scraper.py", line 228, in <module>
with StringIO(csv_data) as input_file:
AttributeError: StringIO instance has no attribute '__exit__'
我知道 StringIO
类没有 __exit__
方法,该方法在 when
完成对该对象的所有操作时调用。
我的回答是如何正确地做到这一点?我想我可以通过子类化它并添加 __exit__
方法来改变 StringIO
类,但我怀疑有更简单的解决方案。
更新:
此外,我尝试了想到的不同组合:
with open(StringIO(csv_data)) as input_file:
with csv_data as input_file:
但是,当然,这些都不起作用。
最佳答案
>>> import csv
>>> csv_data = "some,string\nfor,example"
>>> result = csv.reader(csv_data.splitlines())
>>> list(result)
[['some', 'string'], ['for', 'example']]
关于python - 如何使用字符串作为 csv 阅读器的输入而不将其存储到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41977519/