Parse text file with two 'space' delimiters

I am trying to read this text file in a list of tuples or a numpy array of tuples (x, y) like:

[[0,1], [2,3], [4,5], [2,1], [4,2]]

My text file is:

6
0 1
2 3  4 5  2 1
4 2

I have used this function to separate :

l = 'tiny.txt'
arr = []

def readDatFile(l):
    
    fh = open(eval('l'), 'r+')

    for i in range(0,14):
        arr.append([])
        lines = fh.readline()
        edge = lines.strip().split("  ")
        for parts in edge:
            arr_split = lines.split(" ")
            arr.append(x_y_split[i])
            
        
    return arr

readDatFile(l)

I could figure something out if I knew how the indexing worked after a split applied. Or if given some pointers.

I know the first line is to be omitted too but now want to omit the first line but now I want to know how to parse this file

1 answer

  • answered 2020-11-25 01:40 Ann Zen

    You can use the third parameter of the range() function, the step:

    t = []
    
    with open('file.txt', 'r') as f:
        for l in f:
            l = list(map(int, l.split()))
            for i in range(0, len(l)-1, 2):
                t.append([l[i], l[i+1]])
    
    print(t)
    

    Output:

    [[0, 1], [2, 3], [4, 5], [2, 1], [4, 2]]
    

    Breaking it down:

    1. Define a list to store the sublists:
    t = []
    
    1. Open the specified file in read mode:
    with open('file.txt', 'r') as f:
    
    1. Iterate through the file's lines:
    for l in f:
    
    1. Use the built-in map method to convert each line into a list of integers:
    l = list(map(int, l.split()))
    
    1. range(0, len(l)) is the equivalent of just range(len(l)), but if you want to use the step argument without having to include the name of the keyword argument, you'll need to add in the 0:
    for i in range(0, len(l)-1, 2):
    
    1. Use the slices [i] and [i+1] and append the sublists to the t list defined in the top of the code:
    t.append([l[i], l[i+1]])