StringIO in Python3

python stringio to file
attributeerror: type object '_io.stringio' has no attribute 'stringio'
python3 no stringio
stringio to bytesio
python36 stringio
typeerror: initial_value must be str or none, not bytes
python write bytesio to file
stringio deprecated

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'

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 the message TypeError: Can't convert 'bytes' object to str implicitly, see this answer.

7.5. StringIO — Read and write strings as files, This module implements a file-like class, StringIO , that reads and writes a string buffer (also known as memory files). See the description of file  TextIOWrapper, which extends it, is a buffered text interface to a buffered raw stream ( BufferedIOBase ). Finally, StringIO is an in-memory stream for text. Argument names are not part of the specification, and only the arguments of open () are intended to be used as keyword arguments.


In my case I have used:

from io import StringIO

io — Core tools for working with streams, f = open("myfile.txt", "r", encoding="utf-8"). In-memory text streams are also available as StringIO objects: f = io.StringIO("some initial text data"). The text stream  StringIO ([buffer]) ¶ When a StringIO object is created, it can be initialized to an existing string by passing the string to the constructor. If no string is given, the StringIO will start empty. In both cases, the initial file position starts at zero. The StringIO object can accept either Unicode or 8-bit strings, but mixing the two may take


On Python 3 numpy.genfromtxt expects a bytes stream. Use the following:

numpy.genfromtxt(io.BytesIO(x.encode()))

Python 3.x support (ImportError: No module named 'StringIO') · Issue , When running python handler.py I get the following error: ImportError: No module named 'StringIO' I believe this is related to python 3.x  def parseString(string, handler, errorHandler=ErrorHandler()): try: from cStringIO import StringIO except ImportError: from StringIO import StringIO if errorHandler is None: errorHandler = ErrorHandler() parser = make_parser() parser.setContentHandler(handler) parser.setErrorHandler(errorHandler) inpsrc = InputSource() inpsrc.setByteStream(StringIO(string)) parser.parse(inpsrc) # this is the parser list used by the make_parser function if no # alternatives are given as parameters to the function


Thank you OP for your question, and Roman for your answer. I had to search a bit to find this; I hope the following helps others.

Python 2.7

See: https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html

import numpy as np
from StringIO import StringIO

data = "1, abc , 2\n 3, xxx, 4"

print type(data)
"""
<type 'str'>
"""

print '\n', np.genfromtxt(StringIO(data), delimiter=",", dtype="|S3", autostrip=True)
"""
[['1' 'abc' '2']
 ['3' 'xxx' '4']]
"""

print '\n', type(data)
"""
<type 'str'>
"""

print '\n', np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
"""
[[  1.  nan   2.]
 [  3.  nan   4.]]
"""

Python 3.5:

import numpy as np
from io import StringIO
import io

data = "1, abc , 2\n 3, xxx, 4"
#print(data)
"""
1, abc , 2
 3, xxx, 4
"""

#print(type(data))
"""
<class 'str'>
"""

#np.genfromtxt(StringIO(data), delimiter=",", autostrip=True)
# TypeError: Can't convert 'bytes' object to str implicitly

print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", dtype="|S3", autostrip=True))
"""
[[b'1' b'abc' b'2']
 [b'3' b'xxx' b'4']]
"""

print('\n')
print(np.genfromtxt(io.BytesIO(data.encode()), delimiter=",", autostrip=True))
"""
[[  1.  nan   2.]
 [  3.  nan   4.]]
"""

Aside:

dtype="|Sx", where x = any of { 1, 2, 3, ...}:

dtypes. Difference between S1 and S2 in Python

"The |S1 and |S2 strings are data type descriptors; the first means the array holds strings of length 1, the second of length 2. ..."

StringIO in Python3, You should import stringIo as follows:- from io import StringIO. Below is the code that can be used for fixing the error in Python 3 is as follows:. Is StringIO faster than a series of string appends? I tested a program that wrote large strings, appending strings many times. I found StringIO was faster, in two Python implementations. PyPy: In the PyPy implementation, StringIO was nearly twice as fast as a string append. Note: The if-check in the benchmark loops is just a simple sanity check


You can use the StringIO from the six module:

import six
import numpy

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

StringIO and cStringIO – Work with text buffers using file-like API , If you are looking for examples that work under Python 3, please refer to the StringIO provides a convenient means of working with text in memory using the file API Here are some pretty standard, simple, examples of using StringIO buffers:. Python StringIO and BytesIO are methods that manipulate string and bytes data in memory, this make memory data manipulation use the consistent API as read and write files. StringIO is used to operate string data, and if you want to manipulate binary data, you need to use BytesIO.


Python: Using StringIO and BytesIO for managing data as file object , Now in Python 3.x, we are using io.StringIO or io.BytesIO from the io module, as the StringIO, and cStringIO modules are no longer available in  In Python 3, all strings are represented in Unicode.In Python 2 are stored internally as 8-bit ASCII, hence it is required to attach 'u' to make it Unicode. It is no longer necessary now. Built-in String Methods


ModuleNotFoundError: No module named 'StringIO', Use Python 3, and update the code to read: # instead of: import StringIO import io # A few lines later # instead of portfolio_zip = StringIO.StringIO() portfolio_zip  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 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


Using and supporting Python 3, standard library have been renamed, for example: # Python 2 import Queue import StringIO.StringIO import os os.getcwdu(). # Python 3 import queue import io  StringIO: 1.4, cStringIO: 1.5. StringIO provides a convenient means of working with text in memory using the file API (read, write. etc.). There are two separate implementations. The cStringIO version is written in C for speed, while StringIO is written in Python for portability.