StringIO in Python3

后端 未结 8 1700
清酒与你
清酒与你 2020-11-22 13:33

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

相关标签:
8条回答
  • 2020-11-22 14:12

    In my case I have used:

    from io import StringIO
    
    0 讨论(0)
  • 2020-11-22 14:26

    In order to make examples from here work with Python 3.5.2, you can rewrite as follows :

    import io
    data =io.BytesIO(b"1, 2, 3\n4, 5, 6") 
    import numpy
    numpy.genfromtxt(data, delimiter=",")
    

    The reason for the change may be that the content of a file is in data (bytes) which do not make text until being decoded somehow. genfrombytes may be a better name than genfromtxt.

    0 讨论(0)
  • 2020-11-22 14:28

    try this

    from StringIO import StringIO

    x="1 3\n 4.5 8"

    numpy.genfromtxt(StringIO(x))

    0 讨论(0)
  • 2020-11-22 14:29

    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.

    0 讨论(0)
  • 2020-11-22 14:30

    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))
    
    0 讨论(0)
  • 2020-11-22 14:31

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

    numpy.genfromtxt(io.BytesIO(x.encode()))
    
    0 讨论(0)
提交回复
热议问题