Search code examples
pythoninputfile-read

Python - Preventing closing a file after printing its content


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:
    print(inputFile.read())
    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(pdbFile.read()), 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?


Solution

  • 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.