-1

I recently started programming and I wanted to sort a file, but in the end, this code only returns one line, even though the text file has 65 lines...

f = open(".\\test.txt")
g, u = [], []
a = 0


for i, line in enumerate(f):
    a += 1
    if i%2 == 0:
        g.append(f.readlines()[i])
        print(i),
    elif i%2 == 1:
        u.append(f.readlines()[i])
        print(i),


print(u),
print(g)
IcyTv
  • 405
  • 4
  • 12

3 Answers3

0

You have to do

lines = f.readlines()
for i, line in enumerate(lines):
    a += 1
    if i%2 == 0:
        g.append(lines[i])
        print(i),
    elif i%2 == 1:
        u.append(lines[i])
        print(i),
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
0

open(filename) gives you an iterator over the lines of a file. This iterator will be exhausted after reading all the lines once, any subsequent calls to readlines after the first one will therefore give you an empty list.

Demo:

>>> with open('testfile.txt') as f:
...     a = f.readlines()
...     b = f.readlines()
...     a
...     b
... 
['hello\n', 'stack\n', 'overflow\n']
[]
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

Your for loop starts reading the file line by line. But then its contents go and read the rest of the file in a single readlines call; after that, there's nothing more to be read! So you end up with the first line in line and the second line in g, since you only kept one of the lines that readlines() read.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26