Home > Mobile >  Writing all the values to a text file in Python
Writing all the values to a text file in Python

Time:09-04

The quantity A is constantly updated. I want to write all the values of A to a .txt file and not just the last value. A=120,100,10 where 120 is the value in the first iteration and 10 is the value in the last iteration.

with open('Data_A.txt', 'w') as f:
    writer = csv.writer(f) 
    A=10
    print(A)
    f.writelines('A'  '\n')
    f.write(str(A))

The current output is

A
10

The expected output is

A
120
100
10

CodePudding user response:

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.

CodePudding user response:

First, you should open your file in append mode. Use a instead of w when you open the file.

Secondly, if your code changes the value of A, and whenever it changes, you want it to be printed to the file, use a function you can call instead of directly changing the value of A. This function should write the new value to the file and update the variable's value.

def update_value_of_a(new_value):
    A = new_value
    f.write(str(A)   '\n')

Then, instead of writing something like A = 120 use update_value_of_a(120).

Make sure you define the function in a scope that can access the f variable.

  • Related