python - 如何使用字符串作为 csv 阅读器的输入而不将其存储到文件中

标签 python csv stringio

我正在尝试遍历 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/

相关文章:

python - 数据帧到字符串

python - 我在运行 train.py 时遇到问题,我很困惑

python - 使用 tkinter 更改单击时按钮的浮雕

python - 在追加到 pandas 数据框时创建新列

mysql - 如何修复 "invalid syntax for integer : ' NUM'

python - 分多次?

Ruby 将字符串转换为文件以上传到 FTP

python - scikit-image 将图像保存到字节串

python - 将 session ID 从简单的 salesforce 传递到请求

linux - 仅从 CSV 文件的第 2 行和第 3 行中删除多余的逗号