如何在不将字符串存储到文件的情况下使用字符串作为csv阅读器的输

如何在不将字符串存储到文件的情况下使用字符串作为csv阅读器的输

本文介绍了如何在不将字符串存储到文件的情况下使用字符串作为csv阅读器的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历csv文件中的行.我从Web位置获取csv文件作为string.我知道当数据存储在文件中时如何使用with创建csv.reader.我不知道的是,如何使用csv.reader获取行而不将string存储到文件中.我正在使用Python 2.7.12.

I'm trying to loop through rows in a csv file. I get csv file as string from a web location. I know how to create csv.reader using with when data is stored in a file. What I don't know is, how to get rows using csv.reader without storing string to a file. I'm using Python 2.7.12.

我试图创建这样的StringIO对象:

I've tried to create StringIO object like this:

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完成对该对象的操作时,将调用该方法.

I understand that StringIO class doesn't have __exit__ method which is called when when finishes doing whatever it does with this object.

我的答案是如何正确执行此操作?我想可以通过子类化并添加__exit__方法来更改StringIO类,但是我怀疑有更简单的解决方案.

My answer is how to do this correctly? I suppose I can alter StringIO class by subclassing it and adding __exit__ method, but I suspect that there is easier solution.

更新:

此外,我尝试了各种不同的组合:

Also, I've tried different combinations that came to my mind:

with open(StringIO(csv_data)) as input_file:

with csv_data as input_file:

但是,当然,这些都不起作用.

but, of course, none of those worked.

推荐答案

>>> import csv
>>> csv_data = "some,string\nfor,example"
>>> result = csv.reader(csv_data.splitlines())
>>> list(result)
[['some', 'string'], ['for', 'example']]

这篇关于如何在不将字符串存储到文件的情况下使用字符串作为csv阅读器的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:32