Simply put… consider the following codes
file = open("DJJ.txt", mode = 'w') # construct a .txt file with the mode 'w'
file.write("2\n3") # write 2 & 3 in this .txt file
file = open("DJJ.txt", mode = 'r') # read this file
sum = 0
sqsum = 0
# summation # sum (2+3)
for u in file:
sum += int(u)
print(sum)
# sum of square # sum of square (2^2 + 3^2)
for i in file:
sqsum += int(u)**2
print(sqsum)
The result is
5
0
This code does not calculate sum of square.
The easiest way to correct this is nothing but recall the object file again.
file = open("DJJ.txt", mode = 'r')
for i in file:
sqsum += int(u)**2
print(sqsum)
It looks like the object ‘file’ will be invalid for the second loop; simply speaking, this object
can be used only once. If you want to use it twice, you have to call it again.
My question is why? and is there any other way to correct this issue?
Thanks!
>Solution :
When you open the file with open("DJJ.txt", mode='r'), Python puts a "marker" at the start of the file indicating where to start reading.
When you do:
# summation # sum (2+3)
for u in file:
sum += int(u)
At each iteration, you are moving the "marker" to the next line, until it reaches the end of the file.
When you try to read the file again in the second for loop, the marker is already at the end of the file, so the loop never get to execute, and sqsum doesn’t change.
As suggested by @Adid, you can use file.seek(0) to move the "marker" back to the start of the file.
# sum of square # sum of square (2^2 + 3^2)
file.seek(0)
for i in file:
sqsum += int(i)**2
print(sqsum) # 13
Also, make sure to close the files after you are done working with them:
file.close()