Search code examples
pythonnumpyscitools

Read columns from file where first row is string


What I would like to do is to read in columns from a .dat file. I have been able to do this using scitools.filetable.read_columns(). The problem that I am having is that the first row of my .dat file contains strings. How can I skip the first row?

So for a short example I have the following .dat file:

a   b   c   d   e
1   3   5   7   9
2   4   6   8  10

From this type of .dat file I want to create arrays for each column without the string. When the .dat file would not contain a,b,c,d,e it would be very easy as it would just be:

import scitools.filetable

fp = open("blabla.dat", "r")

a, b, c, d, e = scitools.filetable.read_columns(fp)

Now a would read: [1 2].

However, when I try to do the same thing when a, b, c, d, and e are part of the .dat file, as indicated in my example, scitools does not work since it cannot convert a string to a float. How can I open the file without the first row or create the desired columns?


Solution

  • Use fp.next to advance one line further

    As fp is file descriptor for file open in text mode, iterating over it reads it line by line.

    You can ask fp to read one line further by fp.next() and then pass it to your `scitools.filetable.read_colums(fp)

    Your code would look like this after modification:

    import scitools.filetable
    
    fp = open("blabla.dat", "r")
    fp.next()
    
    a, b, c, d, e = scitools.filetable.read_columns(fp)
    

    Or using context manager for closing the file:

    import scitools.filetable
    
    with open("blabla.dat", "r") as fp:
        fp.next()
    
        a, b, c, d, e = scitools.filetable.read_columns(fp)