How to output to txt (Programming in Python with Processing 3)

Viewed 94

I'm currently working on a project and a part of the project is to output something to the project directory in a sepereate .txt file, I have completed that but I have a problem, everything works GREAT but I don't want to create a new file every single time but I want to have everything and all records stored in only one file and that they just keep adding up, can someone help me?

Here's a part of the code I've came up with, don't bother about the "%d" etc. I just need help with output :

output = createWriter("rekordi.txt")
            output.print("Tvoj zadnji rekord je " + str(millis()/1000-sekunde) + " sekund || ob " + str(datum.strftime("%I:" + "%M" + " %p" + " na " + "%d." + "%b"))) # Write the date to the file
            output.flush()# Writes the remaining data to the file
            output.close()# Finishes the file
2 Answers
with open("rekordi.txt", "a", buffering=0) as f:
      f.write("write some data") 

file mode "a" will append all data to the file
buffering=0 means that data will be written directly to the file (just like using flush() )

What you want to do is open a file in append mode. This will create it if it doesn't exist, and will append to it instead of overwriting it if it does already exist. Something like this should do what you want:

my_file_path = 'output_record.txt'
with open(my_file_path, 'a') as outfile:
    outfile.write(<output data here in string format> + '\n') # \n for newline

The with ... is a context manager block, which means that the file will automatically be closed when that code block exits. And the 'a' second argument to open specifies append mode.

Hope that helps, Happy Coding (and happy Friday)!

Related