Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write string and date to text file in Python 3

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.

like image 421
JSJ Avatar asked Dec 11 '13 01:12

JSJ


3 Answers

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()))
like image 101
abarnert Avatar answered Oct 16 '22 07:10

abarnert


Is this what you want?

from datetime import datetime
with open('scr.txt', 'a') as file:
    file.write('Printed string %s. Recorded at: %s\n' % scr %datetime.now())

Demo:

>>> n = datetime.now()
>>> print("%s"%n)
2013-12-11 08:16:38.029267
like image 44
aIKid Avatar answered Oct 16 '22 07:10

aIKid


I think what you're missing is a flush and close. Python (like many other languages) uses buffers to manage data writes and batch writes to be more efficient. Try adding this after to see if you actually get some output in your file.

file.close()

Additionally, to keep the previous data in your file, you'll want to open in append mode.

file = open("scr.txt", "a")

This way, writes will append to the end of the file instead of truncating and rewriting your scores.

like image 1
Michael Avatar answered Oct 16 '22 07:10

Michael