【问题标题】:how to copy all PNG images from one folder to another if it contain zip than copy it in new folder如果包含 zip,如何将所有 PNG 图像从一个文件夹复制到另一个文件夹,而不是将其复制到新文件夹中
【发布时间】:2021-11-30 12:39:54
【问题描述】:

我正在对图像和 zip 文件夹执行一些脚本,我从一个文件夹复制图像并制作另一个文件夹并复制这些图像。

但如果文件是 zip 文件夹,这里还有一件事,那么我会将该 zip 文件夹复制到一个新目录并复制到该目录。

如何使用 zip 文件夹? 我的图片代码是:

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)

【问题讨论】:

    标签: python image copy


    【解决方案1】:

    如果我正确理解您的问题,您可能想要遍历所有文件,而不仅仅是 jpg 文件。在循环中,您可以检查文件是图像还是 zip 文件并采取相应措施。

    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
    

    【讨论】:

      【解决方案2】:

      谢谢大家在这里解决

      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)
      

      【讨论】:

        猜你喜欢
        • 2014-09-17
        • 2011-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-12
        • 1970-01-01
        相关资源
        最近更新 更多