Python - Preventing closing a file after printing its content

3495 views python

I want to read a file with python, print its contents first, and then do my operations on its data.

Here is my code:

with open("myFile.txt", 'rw') as inputFile:
    for i,j in enumerate(pdbFile):
        do whatever
        count the lines 
print("Number of lines", numberOflines)

The output in this case is numberOfLines = 0.

However, if I comment the command print(, it gives me the correct number of lines. So apparently the file is being closed after reading the file.

How to force python to keep the file open until I finish my calculations?

answered question

No, the file is not closed. You just can't read a file more than once without rewinding to the start.

Add or read once into a variable, then print the variable and loop over the .splitlines(True) result.

1 Answer


After you read() the file, you reached the end of it, and though your file is still open, there is no line left to iterate on.

So, either:

  • don't read it before your for loop, or
  • go back to the start of the file after reading it with `seek(0), or
  • close it and open it again.

posted this

Have an answer?


Please login first before posting an answer.