Search code examples
pythonpython-3.x

Splitting lines from a text file in Python 3


I am trying to split lines on a text file that looks like this:

12/1 AH120 LAX PEK 12:30 21:00
12/2 C32 PEK HNA 12:40 20:00
12/3 D34 MON DOE 3:00 4:00
12/5 A100 ICS SEL 4:00 12:00

Here is the code :

f = open('flights.txt', 'r')
    
for line in f:
    x = f.readline()
    y = x.split()
    print(y)

The problem I have is that instead of giving me lists of each line, it skips a few lines and the output is such that is looks like this:

['12/2', 'C32', 'PEK', 'HNA', '12:40', '20:00']
['12/3', 'D34', 'MON', 'DOE', '3:00', '4:00']

As you can see it is missing the lines beginning with 12/1 and 12/5. I don't know why I am running into this problem. Can anyone tell me what I am doing wrong?


Solution

  • You're reading a line using for line in f already. Then, you read a line using f.readline and use that, but skip the one in line. Therefore, you're missing out on some of the lines

    for line in f:
        y = line.split()
        print(y)