2

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
0

2 Answers 2

1

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)!

Sign up to request clarification or add additional context in comments.

4 Comments

I've tried your method and I still can't get it to work, It just keeps rewriting it over the text I have in the file, I want it to get a highscore and save it in there, and every time I open the game and play it, it saves new highscore below the last one, do you have a solution for that?
The code above works for me. One thing is that you need to append a newline \n if you want it to have each on its own line. I edited my answer to reflect that.
soo if I just copy paste the code above, everything should be working? or do I have to put anything before and aftet it?
I used only the code above. I ran it several times, and saw one line for each call in my output file.
1
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() )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.