Fej*_*ejs 3 python csv stringio
我试图遍历csv文件中的行。我从网站获取csv文件string。我知道如何创建csv.reader使用with时,数据存储在一个文件中。我不知道的是,如何在csv.reader不存储string到文件的情况下使用行。我正在使用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='"')
Run Code Online (Sandbox Code Playgroud)
但是,我收到此错误:
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__'
Run Code Online (Sandbox Code Playgroud)
我知道StringIO该类没有完成此对象的操作__exit__时会调用的方法when。
我的答案是如何正确执行此操作?我想可以StringIO通过子类化和添加__exit__方法来更改类,但是我怀疑有更简单的解决方案。
更新:
另外,我尝试了各种不同的组合:
with open(StringIO(csv_data)) as input_file:
with csv_data as input_file:
Run Code Online (Sandbox Code Playgroud)
但是,当然,这些都不起作用。
小智 5
>>> import csv
>>> csv_data = "some,string\nfor,example"
>>> result = csv.reader(csv_data.splitlines())
>>> list(result)
[['some', 'string'], ['for', 'example']]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4834 次 |
| 最近记录: |