James
James

Reputation: 63

Getting lines from files

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.

Upvotes: 0

Views: 68

Answers (2)

mdegis
mdegis

Reputation: 2448

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]

Upvotes: 3

S.Doe
S.Doe

Reputation: 47

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]

Upvotes: 0

Related Questions