Python中基于for循环中的File name复制文件

ttygqcqt  于 2023-05-05  发布在  Python
关注(0)|答案(1)|浏览(108)

我有一个包含多个xlsx文件的目录。

1-9999.xlsx
10000-19999.xlsx
.
.
.
350000_359999.xlsx
360000_363946.xlsx

我正在尝试根据某些条件复制特定文件。我尝试了以下代码:

import os
import shutil
import glob
import re

path = "G:/Test/destina/"
new_path = "D:/dir/"

files = glob.glob(os.path.join(path, "*.xlsx"))
files

targ = [35, 36]
targs = [f"{i}*.xlsx" for i in targ ]

for file in files:
    for targ in targs:
        if re.search(targ ,file):
            shutil.copy(os.path.join(path, file), new_path)

但它不起作用。有人能帮忙吗?先谢谢你了!

jdgnovmf

jdgnovmf1#

你可以使用Pathlib,它自带glob方法,rglob是递归的

import shutil
from pathlib import Path

path = "G:/Test/destina/"
new_path = "D:/dir/"

targ = [35, 36]
targs = f'[{",".join(str(i) for i in targ)}]*.xlsx'
files = Path(path).rglob(targs)
for file in files:
    shutil.copy(file, new_path)

相关问题