Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting lines from a text file in Python 3

I am trying to using split line 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?

like image 425
kvax12v Avatar asked Dec 11 '22 19:12

kvax12v


2 Answers

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)
like image 75
hlt Avatar answered Dec 27 '22 23:12

hlt


Using for line in f already read lines one by one. Use it like this:

with open('flights.txt', 'r') as f:
    for line in f:
        y = line.split()
        print(y)
like image 25
DainDwarf Avatar answered Dec 27 '22 23:12

DainDwarf