Writing all the values to a text file in Python

Question:

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
Asked By: user19862793

||

Answers:

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.

Answered By: r0den

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('An')


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.

Answered By: Prins
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.