Start New Discussion within our Software Development Community

Hi All,

I am using the below code to write into a text file

# Write into log file
        inp=file(Doc\Log.txt, 'w')
        inp.write('Log file start')

The text file 'Log.txt' is present in 'Doc' folder inside the application folder.
Now I want to create a text file with a time stamp every time the User runs the application and then write contents into it. How do I do this?

Any help is much appreciated!...


Here's an example of how to get the current date and time (as a string) using the datetime module.

import datetime
timestamp = str(
"""result ->
'2009-07-08 01:16:25.968000'

Hope that helps!

Thanks... i used the below code and its working perfectly..
Thanks a lot :)

lt = time.localtime(time.time())
        lt=[lt[1], lt[2], lt[0], lt[3], lt[4],lt[5]]

        strFile = "Log"+"_"+str(lt)+".txt"
        file = open(strFile , "a")
        file.write('Log file starts')

Thanks once again!

you can also try this it would constitute for a lot less coding

import time
#here you can format the date string anyway you want
time_stamp = time.strftime('%Y-%m-%d %H:%M:%S', (time.localtime(time.time())))
#output for time_stamp -> '2009-07-08 14:22:41'
#and format the text file name like such
strFile = "Log_%s.txt"%time_stamp

if you're using windows then having file names with a colon(:) in it is not allowed and you'll get an exception

This question has already been answered. Start a new discussion instead.