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?
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:
read
it before your for
loop, or;seek(0)
, or;