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

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))

Leave a Reply