Search code examples
pythonpython-3.xnumpygenfromtxt

The comments argument of genfromtxt in numpy


I am learning the I/O functions of genfromtxt in numpy. I tried an example from the user guide of numpy. It is about the comments argument of genfromtxt.

Here is the example from the user guide of numpy:

>>> data = """#
... # Skip me !
... # Skip me too !
... 1, 2
... 3, 4
... 5, 6 #This is the third line of the data
... 7, 8
... # And here comes the last line
... 9, 0
... """
>>> np.genfromtxt(StringIO(data), comments="#", delimiter=",")
[[ 1. 2.]
[ 3. 4.]
[ 5. 6.]
[ 7. 8.]
[ 9. 0.]]

I tried below:

data = """#                 \
    # Skip me !         \
    # Skip me too !     \
    1, 2                \
    3, 4                \
    5, 6 #This is the third line of the data    \
    7, 8                \
    # And here comes the last line  \
    9, 0                \
    """
a = np.genfromtxt(io.BytesIO(data.encode()), comments = "#", delimiter = ",")
print (a)

Result comes out:

genfromtxt: Empty input file: "<_io.BytesIO object at 0x0000020555DC5EB8>" warnings.warn('genfromtxt: Empty input file: "%s"' % fname)

I know the problem is with data. Anyone can teach me how to set the data as shown in the example? Thanks a lot.


Solution

  • Try below. First, dont use "\". Second, why are you using .BytesIO() use StringIO()

    import numpy as np
    from StringIO import StringIO
    
    data = """#                 
        # Skip me !     
        # Skip me too !     
        1, 2                
        3, 4                
        5, 6 #This is the third line of the data    
        7, 8                
        # And here comes the last line  
        9, 0                
        """
    
        np.genfromtxt(StringIO(data), comments="#", delimiter=",")
    
        array([[ 1.,  2.],
               [ 3.,  4.],
               [ 5.,  6.],
               [ 7.,  8.],
               [ 9.,  0.]])