Issues in your attempt: You need to append to the file rather than overwriting it each time i.e. use the 'a'
instead of 'w'
mode.
Solution - Invoke function: Here is a sample solution demonstrating how to append to a file by invoking a function:
def create():
with open('Data_A.txt', 'w') as f:
f.write('A\n')
def update(value):
with open('Data_A.txt', 'a') as f:
f.write(f'{value}\n')
return value
# example
create()
a = update(120)
a = update(100)
a = update(10)
The code is in a function that you can call each time you change the value.
We can open the file outside of the update
function but this would mean that the file remains open until released e.g. the program is closed. Opening the file in the update
function releases the file straightaway after the appending is complete but would be slower if you are making a lot of calls repeatedly.
Similarly, we can access the global variable directly in the update
function but this is generally discouraged. Instead, we return the value.
Alternative solutions: You can use object-oriented approach with properties.