Python – Adding a date to filename

Python – Adding a date to filename

Mark January 1, 2021

As a total Noob to Python, it may seem a pretty simple to add date to the end of a file name … but it took me an hour to work it out *facepalm inserted here*

First in my script, I imported the “date” portion of the from the “datetime” libary,

from datetime import date                   
today = date.today()
print("Today's date:", today)

When creating the file (and this is the bit that took me an hour to find), you will need to set a verable which uses “today”

Date = (today)

Once you have set the date you can add this into the file name by using “+ (str(Date))”

with open('d:/Test/Webversion-' + (str(Date)) + '.txt', 'w') as output:       
output.write("Today's Date - ")
output.write("\n")

The bit that took me a little bit of time was getting the single qoute marks correct in the correct place, you can see how I have used this in a script on my GitHub …

https://github.com/MarkSpencerIT/SecurityTools