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

允我心安 提交于 2019-12-08 04:00:26

问题


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)  

回答1:


I just tested the following on a file named "temp" which was changed to "temp_Sep-15-14-08:42:57"

FilePath = 'temp' # replace the temp with your file path/name
modifiedTime = os.path.getmtime(FilePath) 

timeStamp =  datetime.datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S")
os.rename(FilePath,FilePath+"_"+timeStamp)



回答2:


This should do it:

timestamp = (datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S"))
newName = 'c:\\syncwork\\ace\\files\\ESAL_P\\Backup\\ESAL_P.txt.' + timestamp


来源:https://stackoverflow.com/questions/25851314/making-a-backup-file-appending-date-time-moving-file-if-the-file-exists-pyt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!