Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use StringIO in Python3?

I am using Python 3.2.1 and I can't import the StringIO module. I use io.StringIO and it works, but I can't use it with numpy's genfromtxt like this:

x="1 3\n 4.5 8"         numpy.genfromtxt(io.StringIO(x)) 

I get the following error:

TypeError: Can't convert 'bytes' object to str implicitly   

and when I write import StringIO it says

ImportError: No module named 'StringIO' 
like image 739
Babak Abdolahi Avatar asked Aug 11 '12 11:08

Babak Abdolahi


People also ask

How do you define a StringIO in Python?

The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.

How do you define StringIO?

Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character '\0'. Declaration of strings: Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string.

How do I write a StringIO file?

Python – Write String to Text FileOpen the text file in write mode using open() function. The function returns a file object. Call write() function on the file object, and pass the string to write() function as argument. Once all the writing is done, close the file using close() function.


1 Answers

when i write import StringIO it says there is no such module.

From What’s New In Python 3.0:

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

.


A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):

try:     from StringIO import StringIO ## for Python 2 except ImportError:     from io import StringIO ## for Python 3 

Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing StringIO module. For a more direct solution the message TypeError: Can't convert 'bytes' object to str implicitly, see this answer.

like image 165
Brent Bradburn Avatar answered Nov 27 '22 04:11

Brent Bradburn