0

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?

UmutJean
  • 1
  • 1
  • 1
    are you sure the input file has more than one line that starts with `From: ` with the first letter captical and the last letter being space, and no spaces before it ? – Ahmed AEK Oct 15 '22 at 18:01
  • Yes. They are like this : "From: mike From: john From: dana From: jake" and when i change the positions, the always the first line is printed. Others are ignored – UmutJean Oct 15 '22 at 18:03
  • can you add that to the question, without any formatting or modification, just plain press enter twice then copy-paste the file content, or a few lines of it, i there is a chance the file has some bad formatting or unicode characters that are causing this problem. – Ahmed AEK Oct 15 '22 at 18:08
  • 2
    `len(fhand.read())` - that advances the file position all the way to the end. – user2357112 Oct 15 '22 at 18:18
  • 2
    (This is why it's important to verify that what you post actually reproduces the problem when run. It's good to simplify and strip down the reproducer for a bug, but it's even more important to make sure it still reproduces the bug.) – user2357112 Oct 15 '22 at 18:19
  • I found the problem : counting the total number of characters in the file (in the same for loop) was creating the problem. With that line erased, the for loop prints all the values. Thanks guys. – UmutJean Oct 15 '22 at 18:20
  • This shows the value of running the EXACT SAME CODE as in your question. Had you run the code that you had in your question earlier, you would have solved your own problem. – RufusVS Oct 15 '22 at 18:20
  • 1
    Amen to that @RufusVS. Becoming a programmer requires learning more than Python. And I'm determined ✊ – UmutJean Oct 15 '22 at 18:26

0 Answers0