[Python] Making a backup file + appending date time + moving file if the file exists. PYTHON

Discussão em 'Python' iniciado por Stack, Junho 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have a few of the pieces of this working but I'm struggling with putting them together.

    I would like to take a file, move it to a backup folder, get the date time from that file, and append it to the file's name / change the file's name to file name + date time.

    This part gets the date time in the format I want it. (print line is the date time formatted properly, but I don't need to print this line)

    Filepath = "C:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt"
    modifiedTime = os.path.getmtime(Filepath)
    firstFile = os.path.getmtime(Filepath)

    print (datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S"))


    This part will rename / move the file (But it's missing the datetime)

    prevName = 'c:\\syncwork\\ace\\files\\ESAL_P\\ESAL_P.txt'
    newName = 'c:\\syncwork\\ace\\files\\ESAL_P\\Backup\\ESAL_P.txt'

    os.rename(prevName, newName)


    How do I turn the print line with the formatting that I like into a string and append it to the end of the newName line?

    AFTER my question was answered My final code looked like this:

    Filepath = "C:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt"
    modifiedTime = os.path.getmtime(Filepath)



    timestamp = datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%Y_%H.%M.%S")

    prevName = 'c:\\SyncWork\\ACE\\Files\\ESAL_P\\ESAL_P.txt'
    newName = 'c:\\SyncWork\\ACE\\Files\\ESAL_P\\Backup\\ESAL_P'

    os.rename(prevName, newName+"_"+timestamp + ".txt")
    print(newName)

    Continue reading...

Compartilhe esta Página