Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string as input for csv reader without storing it to file

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.

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='"')

However, I'm getting this error:

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__'

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

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.

Update:

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.

like image 680
Fejs Avatar asked Feb 01 '17 10:02

Fejs


People also ask

How do I write a string in a CSV file?

Steps for writing a CSV file First, open the CSV file for writing ( w mode) by using the open() function. Second, create a CSV writer object by calling the writer() function of the csv module. Third, write data to CSV file by calling the writerow() or writerows() method of the CSV writer object.

Can CSV reader read text?

Reading from a CSV file is done using the reader object. The CSV file is opened as a text file with Python's built-in open() function, which returns a file object. This is then passed to the reader , which does the heavy lifting.

Can you read and write to a CSV file at the same time?

You can read and simultaneously write to a second file, then atomically move the second to overwrite the first - which is how these things are usually done.

How do I input a CSV file?

You can import data from a text file into an existing worksheet. On the Data tab, in the Get & Transform Data group, click From Text/CSV. In the Import Data dialog box, locate and double-click the text file that you want to import, and click Import.


1 Answers

>>> import csv
>>> csv_data = "some,string\nfor,example"
>>> result = csv.reader(csv_data.splitlines())
>>> list(result)
[['some', 'string'], ['for', 'example']]
like image 112
Thomas Lehoux Avatar answered Sep 30 '22 18:09

Thomas Lehoux