Change Name of file after copy to new directory
Question:
I have got a python script to update external excel link, then copy to a new directory but I want to prefix it with the date as its going to occur a few times a month. At the moment, the script only copies the file into the same directory and changes the name.
import os
import shutil
import fnmatch
from datetime import datetime
prefix = datetime.today().strftime('%y%m%d')
dir_src = ("D:\Users\cdoyle\Desktop\TGround\")
dir_dst = ("D:\Users\cdoyle\Desktop\TGround\GUID\")
filename = ("All Facilities - GUID Duplicates Tracking.xlsx")
outputname = os.path.join(prefix + "-" + filename)
srcfile = ("D:\Users\cdoyle\Desktop\TGround\All Facilities - GUID Duplicates Tracking.xlsx")
desfile = ("D:\Users\cdoyle\Desktop\TGround\GUID\All Facilities - GUID Duplicates Tracking.xlsx")
if os.path.exists(srcfile):
shutil.copy( dir_src + filename, dir_dst)
print(filename)
if os.path.exists(desfile):
os.rename("D:\Users\cdoyle\Desktop\TGround\GUID\All Facilities - GUID Duplicates Tracking.xlsx", outputname)
print (outputname)
Answers:
I think you could simply replace your last if with:
if os.path.exists(desfile):
os.rename(dir_dist + filename, dir_dist + prefix+ '_' + filename)
print (outputname)
If possible, avoid spaces in file and folder names. It could lead to some problems later.
I have got a python script to update external excel link, then copy to a new directory but I want to prefix it with the date as its going to occur a few times a month. At the moment, the script only copies the file into the same directory and changes the name.
import os
import shutil
import fnmatch
from datetime import datetime
prefix = datetime.today().strftime('%y%m%d')
dir_src = ("D:\Users\cdoyle\Desktop\TGround\")
dir_dst = ("D:\Users\cdoyle\Desktop\TGround\GUID\")
filename = ("All Facilities - GUID Duplicates Tracking.xlsx")
outputname = os.path.join(prefix + "-" + filename)
srcfile = ("D:\Users\cdoyle\Desktop\TGround\All Facilities - GUID Duplicates Tracking.xlsx")
desfile = ("D:\Users\cdoyle\Desktop\TGround\GUID\All Facilities - GUID Duplicates Tracking.xlsx")
if os.path.exists(srcfile):
shutil.copy( dir_src + filename, dir_dst)
print(filename)
if os.path.exists(desfile):
os.rename("D:\Users\cdoyle\Desktop\TGround\GUID\All Facilities - GUID Duplicates Tracking.xlsx", outputname)
print (outputname)
I think you could simply replace your last if with:
if os.path.exists(desfile):
os.rename(dir_dist + filename, dir_dist + prefix+ '_' + filename)
print (outputname)
If possible, avoid spaces in file and folder names. It could lead to some problems later.