Search code examples
pythonpython-3.xdirectorycopysubdirectory

copy all files and folder inside a dir except .jpg and .png files in python


Folder Structure:

rootfoder:
    subfoler1:
        image.jpg
    subfoler2:
        image.png
        text.txt
    subfoler3

I have to copy all the files/folder inside root folder to des folder. But .jpg and .png file should be not copied and empty folder should also be copied.

Can this be done in python using any lib?


Solution

  • Use shutil for this:

    import shutil
    
    shutil.copytree('/tmp/source', '/tmp/target' , ignore=shutil.ignore_patterns('*.jpg', '*.png'))
    

    shutil provides an ignore_patterns function to skip certain files on tree copying.

    HTH, ferdy