Reputation: 9
I'd like to create a Python script that creates a log file with a unique name. If possible, I'd like the unique name to include a date-time stamp.
I can create a string with the name that I like (unique with a timestamp):
import os, datetime, copy
lastPart = datetime.datetime.now().strftime('%m/%d/%Y/%s')
logName = 'log' + lastPart + '.txt'
print logName
The above demonstrates how to create a variable with an ideal name of the log.
I want to write to this log file throughout the script. I'll be sending the results of various operations to this log file. Naturally the name of this log file will vary from run to run (given the timestamp). How do I create a file based on a variable name in Python? How do I reference it in my static code on different lines? I want to write to it. I know the >> works in Python.
Upvotes: 0
Views: 555
Reputation: 9
Hugh should get credit. Here is the solution (as my version of Linux didn't like the slashes (/) in the file name):
import os, datetime, copy lastPart = datetime.datetime.now().strftime('%m.%d.%Y.%s') logName = 'log' + lastPart + '.txt'
log_file = open(logName, "a") # in append mode
log_file.write("this is a test\n")
Upvotes: 0
Reputation: 56654
The name of the file may vary;
that does not mean you need to change the name of the variable that holds the name of the file.
import os, datetime, copy
lastPart = datetime.datetime.now().strftime('%m/%d/%Y/%s')
logName = 'log' + lastPart + '.txt'
log_file = open(logName, "a") # in append mode
log_file.write("this is a test\n")
Upvotes: 2