Write string and date to text file in Python 3

python, python-3.x

Solution

You're not calling `file.close()` anywhere. Until you do that (or `file.flush()`), there is no guarantee that anything will be written to the file; it could all be sitting around in a buffer somewhere.

A better way to do this is to use a `with` statement, so you don't have to remember to call `close`.

This is explained indirectly by Reading and Writing Files in the tutorial. The reference documentation explaining it in detail is scattered around the `io` docs, which can be hard for a novice to understand.

Also, opening the file in `'w'` mode will replace the entire file each time. You want to append to the existing file, which means you need `'a'` mode. See the tutorial section Reading and Writing Files or the `open` documentation for more details.

Adding a new line, you've already got right, with the `\n` in the format string.

Finally, you can get the date and time with the `datetime` module. If you don't mind the default ISO date format, you can just format the `datetime` object as a string.

Putting it all together:

import datetime

with open("scr.txt", mode='a') as file:
    file.write('Printed string %s recorded at %s.\n' % 
               (scr, datetime.datetime.now()))

Problem

Trying to figure out how to out a guessing game score plus the date & time to a text file with a new line each time, keeping the old text. This is what I've got so far; ``` print('You scored %s.' % scr) file = open("scr.txt", mode='w') file.write('Printed string %s.\n' % scr) ``` This isn't working by the way - it's showing that an edit has been made to the text file but nothing is showing up in the text file - so I'm doing something wrong. I want the text file to read 'Printed string scr recorded at date & time. As well as wanting a new line each time upon writing and keeping what has been written before. Thanks in advance. Any help would be greatly appreciated.

Original source