复制Excel从源到目的地

2024-03-28 11:16:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图复制源目录中以XXXXX开头的excel文件,并将它们放入与excel文件的第一个XXXXX匹配的目标目录中。我也只想匹配目标文件夹的第一个XXXXX。文件放入目标文件夹后,我想更改名称。下面的代码只允许我将src excel放到一个名为only XXXXX not的文件夹中(例如“XXXXX folder”),它只重命名根目录中的文件。思想?你知道吗

for root, dirs, files in os.walk(dir_src):
    for file in files:
        if file.endswith(".xlsx"):
            filename = file[:5]
            shutil.copy((dir_src +'\\'+file), (dir_dst + '\\'+ filename))
            for filename in glob.glob(os.path.join(dir_dst + '\\'+ filename, '*.xlsx')):
                    os.rename(filename, 'Weekly_Claims.xlsx') 

Tags: 文件insrc文件夹目标forosdir
1条回答
网友
1楼 · 发布于 2024-03-28 11:16:44

我想我知道了。。。尽管外面有人可能会用一种更像Python的方式

import glob,os   
import shutil
import re

for root, dirs, files in os.walk(dir_src):
    for file in files:
        if file.endswith(".xlsx"):
            filename = file[:5]
            src_file = os.path.join(dir_src, file)         
            #search destination subdirectory for folder 
            for root, dirs, files in os.walk(des_test):
                for name in dirs:
                    #if the source filename equals first 5 of the subdirectory name, copy to the des_file
                    if filename == name[:5]:
                        dst_file = os.path.join(des_test, name)
                        shutil.copy(src_file, dst_file)

相关问题 更多 >