0

I am trying to get a to be the first line of the file and b to be the second.

This prints nothing.

f = open(filename)
line = f.readline().strip()
while line:
    a = f.readline()
    b = f.readline()
    line = f.readline()
print(a)
print(b)

I want to assign specific lines to variables, not just read all of them.

John Moutafis
  • 22,254
  • 11
  • 68
  • 112
James
  • 63
  • 1
  • 1
  • 7

2 Answers2

3

Check the tutorial first please, it says:

If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

lines = f.readlines()
a = lines[0]
b = lines[1]
mdegis
  • 2,078
  • 2
  • 21
  • 39
0
lines =[]
with open(filename) as f:
    i =0
    for line in f:
        lines[i] = line
        i += 1

print '1st Line is: ', lines[0]
print '2st Line is: ', lines[1]
S.Doe
  • 49
  • 1
  • 10