Python : startswith(...) finds only the first line that contains the text. Then breaks for loop

31 Views Asked by At

I am using Spyder as the IDE (Python ver 3.8). When I implement the following code :

count = 0

fhand = open('deneme.txt')     # file handle
for line in fhand:
    if line.startswith('From:'):
        print(line.rstrip())              # rstrip() is used to avoid new lines
        count += 1   
        print('number of lines read: ', count)
        print('char count',len(fhand.read()),' after the read line')
print('count : ', count)

I get only the first line that starts with 'From:' , the count is printed only once as 1 in the loop, then agian as 1 after the loop. There are 4 lines in the txt file that start with 'From :' I changed their positions in the txt file and always only the first one is printed. The input file is as follows :

beginning_of_file
line_1
From: mike
From: john
From: dana
From: jake
2
3
end_of_file

I guess Python flushes the file handle automatically after the first use. How can I keep the file handle in the memory until all the for loop iterations are finished? Or is it something else?

0

There are 0 best solutions below