0

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.

2 Answers 2

2

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")
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.