Search code examples
pythondatestring-formatting

Saving a file with a date variable extension


My aim is to check a text file for a size (> 0 bytes) and if True, copy the file to another directory. What i would like to add is a date to the file by generating a date variable. The part i am unable to figure out is how to add the date variable when I copy the file. The below code works fine except adding the variable called yesterday to the filename. Any ideas on how do perform this last part of the code ?

import os
import shutil
import datetime

# a variable called yesterday will be generated (yesterdays date)
today = datetime.date.today()
one_day = datetime.timedelta(days=1)
yesterday = today - one_day

# Check if file is True

file_path = r"C:\temp\Missing_File.txt"
if os.stat(file_path).st_size > 0:
    shutil.copy("C:/temp/Missing_File.txt", "C:/temp2/Missing_File.txt")

Solution

  • Use str.format():

    shutil.copy("C:/temp/Missing_File.txt", "C:/temp2/Missing_File_{}.txt".format(yesterday))
    

    If you have Python 3.6+, another option is to use an f-string:

    shutil.copy("C:/temp/Missing_File.txt", f"C:/temp2/Missing_File_{yesterday}.txt")
    

    You can also customize stringification of a date object by specifying a format string in the placeholder, e.g.:

    >>> import datetime
    >>> yesterday = datetime.date.today() - datetime.timedelta(days=1)
    >>> "C:/temp2/Missing_File_{:%A}.txt".format(yesterday)
    'C:/temp2/Missing_File_Sunday.txt'