Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8319031
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T22:10:59+00:00 2026-06-08T22:10:59+00:00

My question is related to file-input in Python, using open() . I have a

  • 0

My question is related to file-input in Python, using open(). I have a text file mytext.txt with 3 lines.
I am trying to do two things with this file: print the lines, and print the number of lines.

I tried the following code:

input_file = open('mytext.txt', 'r')
count_lines = 0
for line in input_file:
    print line
for line in input_file:
    count_lines += 1
print 'number of lines:', count_lines

Result: it prints the 3 lines correctly, but prints “number of lines: 0” (instead of 3)


I found two ways to solve it, and get it to print 3:

1) I use one loop instead of two

input_file = open('mytext.txt', 'r')
count_lines = 0
for line in input_file:
    print line
    count_lines += 1
print 'number of lines:', count_lines

2) after the first loop, I define input_file again

input_file = open('mytext.txt', 'r')
count_lines = 0
for line in input_file:
    print line
input_file = open('mytext.txt', 'r')
for line in input_file:
    count_lines += 1
print 'number of lines:', count_lines

To me, it seems like the definition input_file = ... is valid for only one looping, as if it was deleted after I use it for a loop. But I don’t understand why, probably it is not 100% clear to me yet, how variable = open(filename) treated in Python.

By the way, I see that in this case it is better to use only one loop. However, I feel I have to get this question clear, since there might be cases when I can/must make use of it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T22:11:01+00:00Added an answer on June 8, 2026 at 10:11 pm

    The file handle is an iterator. After iterating over the file, the pointer will be positioned at EOF (end of file) and the iterator will raise StopIteration which exits the loop. If you try to use an iterator for a file where the pointer is at EOF it will just raise StopIteration and exit: that is why it counts zero in the second loop. You can rewind the file pointer with input_file.seek(0) without reopening it.

    That said, counting lines in the same loop is more I/O efficient, otherwise you have to read the whole file from disk a second time just to count the lines. This is a very common pattern:

    with open('filename.ext') as input_file:
        for i, line in enumerate(input_file):
            print line,
    print "{0} line(s) printed".format(i+1)
    

    In Python 2.5, the file object has been equipped with __enter__ and __exit__ to address the with statement interface. This is syntactic sugar for something like:

    input_file = open('filename.txt')
    try:
        for i, line in enumerate(input_file):
            print line,
    finally:
        input_file.close()
    print "{0} line(s) printed".format(i+1)
    

    I think cPython will close file handles when they get garbage collected, but I’m not sure this holds true for every implementation – IMHO it is better practice to explicitly close resource handles.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a modeling question related to profiles. Firstly, I have looked into using
I have a time related php question! I have html input boxes that asks
This question is related to the previous post. How to save file and read
Another question related to this one . I have a List<SortableObjects> that is the
I have a question related to this one . I don't want to do
This question here is related to Haskell Input Return Tuple I wonder how we
I have a basic upload form: <form method=post action= enctype=multipart/form-data > <input type=file name=logo>
Two (related?) questions here. I was trying to write a program to start an
In a related question we explored using ProcessBuilder to start external processes in low
Maybe you can help me with a question I have, related to C++ language:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.