Separating values from text file in python

Viewed 82

I am trying to read in a text file with the following data:

 362  147
 422   32
 145   45
 312   57
  35  421
 361  275

and I want to separate the values into pairs so 362 and 147 would be pair 1, 422 and 32 pair 2 and so on.

However I run into a problem during the 5 pair which should be 35,421 but for some reason my code does not split this pair correctly, i think this is because of the spaces since only this pair has a two digit number and then a 3 digit number. But I'm not sure how to fix this, here's my code:

def __init__(filename):
    f = open(filename, "r") #reads file
    #print (f.read) # test if file was actually read 
    f1 = f.readlines() # reads individual lines
    counter = 0
    for line in f1: 
        values = line.split("  ") #splits the two values for each line into an array
        value1 = values[0].strip() #.strip removes spaces at each values
        value2 = values[1].strip()
        counter = counter + 1
        print('\npair: {}'.format(counter))
        #print(values)
        print(value1)
        print(value2)

The output I get:

pair: 1
362
147

pair: 2
422
32

pair: 3
145
45

pair: 4
312
57

pair: 5

35

pair: 6
361
275
2 Answers

Try this :

def __init__(filename):
    with open(filename, "r") as f:
        lines = [i.strip() for i in f.readlines()]
        for line_num, line in enumerate(lines):
            p1, p2 = [i for i in line.split() if i]
            print(f"pair: {line_num+1}\n{p1}\n{p2}\n\n")

Note : Always try to use with open(). In this way python takes care of closing the file automatically at the end.

The problem with your code is that you're not checking whether the words extracted after splitting values are empty string or not. If you print values for each line, for the pair 5, you'ld notice it is ['', '35', '421\n']. The first value of this one is an empty string. You can change your code to this :

def __init__(filename):
    f = open(filename, "r") #reads file
    #print (f.read) # test if file was actually read 
    f1 = f.readlines() # reads individual lines
    counter = 0
    for line in f1: 
        values = line.split() #splits the two values for each line into an array; Addendum .split(" ") is equivalent to .split()
        values = [i for i in values if i] #Removes the empty strings
        value1 = values[0].strip() #.strip removes spaces at each values
        value2 = values[1].strip()
        counter = counter + 1
        print('\npair: {}'.format(counter))
        #print(values)
        print(value1)
        print(value2)

Change this line:

values = line.split("  ")

to:

values = line.split()
Related