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

Updating values in a txt file using Python

I am generating numbers in a specific range with a specific stepsize. I am saving these numbers to a .txt file as shown below. But I want to update this file everytime I run the code. I present the current and expected output.

Start = 0
End = 11
Stepsize = 1

filename = f"All_values.txt"   

for i in range(Start, End, Stepsize):
    with open(filename, 'a') as f:
        f.writelines('\n')
        f.write(str(i))

The current output after running the code twice is

0
1
2
3
4
5
6
7
8
9
10
0
1
2
3
4
5
6
7
8
9
10

The expected output after running the code twice is

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

0
1
2
3
4
5
6
7
8
9
10

>Solution :

You have two problems:

You need to use the "w" option to write the file instead of "a", which appends to the file.

And since you do not want to delete and rewrite the file after each number printed, you have to exchange the loops.

Start = 0
End = 11
Stepsize = 1

filename = f"All_values.txt"   

with open(filename, 'w') as f:
    for i in range(Start, End, Stepsize):
        f.writelines('\n')
        f.write(str(i))
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