Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

(python) reading data from a file (mode = 'r') does not work for the second recall

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading