简体   繁体   中英

Copy files with specific text at the end of their (file) names from one folder to other folder

I have 23000 files in one folder and want to copy files with their names ending with some specific text to other folder using python. I used the following code, though it runs successfully but it doesn't copy the file in the destination folder.

import os
import shutil
path = "D:/Snow_new/test"
outpath = "D:/Snow_new/testout"
for f in os.listdir(path):
    if f.endswith("clip_2"):
        shutil.copyfile(os.path.join(path, f), outpath)

you are trying to copy files to a single filename again and again, so to fix it you will have to add the filename with outpath for every file

import os
import shutil
path = "D:/Snow_new/test"
outpath = "D:/Snow_new/testout"

if not os.path.isdir(outpath):
    os.mkdir(outpath)
else:
    shutil.rmtree(outpath)
    os.mkdir(outpath)

for f in os.listdir(path):
    f2, ext = os.path.splitext(f)
    if f2.endswith("clip_2"):
        shutil.copyfile(os.path.join(path, f), os.path.join(outpath, f))

before running the above code make sure that you remove D:/Snow_new/testout completly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM