How to make it so that each change change option is written on a new line

Viewed 32
my_file = open("Data.txt", "w+")
    Data="Hi"
    next_line="\n"
    my_file.write(Data)
    my_file.write(next_line)
    my_file.close() 

Imagine that the data variable will change its value when the program is running

1 Answers

Instead of opening the file in write mode, you can open it in append mode using 'a'.

def add_change(addition):
    with open("Data.txt",'a') as f:
        f.write(addition+"\n")


add_change("new")

Also, by opening the file using with open("Data.txt") means that you don't need to worry about having to close the file with file.close() as this is dealt with already.

The 'a' works by inserting text at the current file stream position which (by default) is at the end of the file.

Related