iFunction
iFunction

Reputation: 1268

readline with for loop issue

I have a .txt file with 10 sort lines of text (three comma separated words each), but the following only reads four of the lines in the text file:

def main():
    path = '/path/to/file.txt'
    f  = open(path, 'r')
    for line in f:
        s = f.readline()
        print(s)
    f.close
main()

but this will read all the lines but into a list:

def main():
    path = '/path/to/file.txt'
    f  = open(path, 'r')
    s = f.readlines()
    print(s)
    f.close
main()

Why doesn't the for loop work?

Upvotes: 2

Views: 9164

Answers (4)

Maxime de Pachtere
Maxime de Pachtere

Reputation: 283

When you open your file.txt, you got an _io.TextIOWrapper object as f.

for line in f: will iterate on the f iterator to yield each line of your file successively,line by line, into your line variable. You can see how iterators work here.

When the f iterator moves one line after the start of your loop, you read another line with your s = f.readline() and that moves your iterator one more line ahead. When you end your first loop, another line of f is read with your for line in f: then, you skip that line by reading the next line with s = f.readline().

Your code will work with

def main():
    path = '/path/to/file.txt'
    with open(path, 'r') as f:
        for line in f:
            print(line)

main()

Upvotes: 1

Rolf of Saxony
Rolf of Saxony

Reputation: 22433

for line in f: is already iterating over the lines in the file, you are then attempting to read a line within that iteration. Just use the value of line and forget about s

Upvotes: 0

YGouddi
YGouddi

Reputation: 361

When using for line in f you're already reading a line. So it's useless to do readline() since it will read the next line which explains why you get 4 lines read instead of 10.

Upvotes: 3

Richy
Richy

Reputation: 380

This would work to get all the lines:

with open('/path/to/file.txt') as fp:
    for line in fp.read().split('/n'):
        print(line)

Upvotes: 1

Related Questions