Search code examples
pythonlistpandastextsplit

Creating lists from a text file by splitting it vertically


I want to split this text file into 3 (called x, y, and e) lists using Python and I can't seem to do it.

This is what the text file (called data) looks like:

x y e
-2 2.1 0.170358869161
0 2.4  0.170202773308
2 2.5  -0.138557648063
4 3.5  0.187965696415
6 4.2  -0.473073365465

This is the code I have so far that doesn't work:

x=[]
y=[]
e=[]

try: 
    data = open('data.txt', 'rt')
except:
    sys.exit('cannot find file')

with data:    
    try:
        x.append(data[:1])
        y.append(data[2:3])
        e.append(data[4:5])
except:
    sys.exit('cannot create lists')

Solution

  • Do this:

    with data as f:     # f is the file object
        for line in f:  # you can iterate over a file object line-by-line
            xi, yi, ei = line.split()
            x.append(xi)
            y.append(yi)
            e.append(ei.strip()) # ei will have a \n on the end
    

    You can coerce them to ints or floats when appending them, if your assumptions about their shape are correct.

    If you have pandas, I recommend read_csv:

    >>> import pandas as pd
    >>> pd.read_csv('data.txt', delim_whitespace=True)
       x    y         e
    0 -2  2.1  0.170359
    1  0  2.4  0.170203
    2  2  2.5 -0.138558
    3  4  3.5  0.187966
    4  6  4.2 -0.473073