python-3.x 复制到新目录后更改文件名

iqih9akk  于 2023-02-06  发布在  Python
关注(0)|答案(1)|浏览(127)

我有一个python脚本更新外部excel链接,然后复制到一个新的目录,但我想前缀它的日期,因为它会发生几次,一个月。目前,脚本只复制到同一目录的文件,并改变名称。

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)
wfsdck30

wfsdck301#

我想你可以简单地把最后一个如果换成:

if os.path.exists(desfile):
    os.rename(dir_dist + filename, dir_dist + prefix+ '_' + filename)
    print (outputname)

如果可能,请避免在文件名和文件夹名中使用空格。这可能会导致以后出现一些问题。

相关问题