简体   繁体   中英

how to copy all PNG images from one folder to another if it contain zip than copy it in new folder

I am doing some scripting on images and zip folder where I am copying images from one folder and making another folder and copy that images.

But one more thing here if the file is a zip folder then I will copy that zip folder to a new directory and copy to that directory.

How it will be possible for a zip folder?? my code for images is:

import glob
import shutil
import os

src_dir = "your/source/dir"
dst_dir = "your/destination/dir"
for jpgfile in glob.iglob(os.path.join(src_dir, "*.jpg")):
    shutil.copy(jpgfile, dst_dir)

If I understand your question correctly you might want to loop over all files, not only the jpg files. Inside the loop you can check if the file is an image or a zip file and act accordingly.

from shutil import copyfile
import os

source = "your_source"
dest = "your_destination"

for file in os.listdir(source):
    if(file.endswith(".jpg")):
        copyfile(source,destination)
    elif(file.endswith(".zip")):
        destination = "new_destination"
        #do more stuff

Thanks everyone here is the solution

import os 
    # Create directory
    dirName = 'new'
    zipdir = 'zip'
    src_dir = "/home/ali/Desktop/test/"
    dst_dir = "/home/ali/Desktop/test2/"
    for file in os.listdir(src_dir):
        if file.endswith(".png" or '.jpg'):
            try:
                # Create target Directory
                path = os.path.join(dst_dir, dirName)
                os.mkdir(path)
                print("Directory " , dirName ,  " Created ") 
            except FileExistsError:
                print("Directory " , dirName ,  " already exists")
            shutil.copy((src_dir+file) , path)
        if file.endswith(".zip"):
            try:
                # Create target Directory
                path = os.path.join(dst_dir, zipdir)
                os.mkdir(path)
                print("Directory " , dirName ,  " Created ") 
            except FileExistsError:
                print("Directory " , dirName ,  " already exists")
            shutil.copy((src_dir+file) , path)

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