Home > database >  I am writing the python script for copy the certain multiple image files (.jpg)from one folder by gi
I am writing the python script for copy the certain multiple image files (.jpg)from one folder by gi

Time:06-08

I have large jpeg files dataset.file name are like this 965_0000000005_0000000001_20211105153826.jpg 965_0000000005_0000000002_20211105153826.jpg . .

966_0000000005_0000000001_20211105153832.jpg . .

967_......... . .

so on... I want to make the python script to copy the file by giving multiple inputs the file names according 965, 966, 988, ., .,.. and then it will copy to new folder. I am trying to copy multiple image files from one folder to another using the following code

import os

import shutil

import datetime




def copyImage (num):

    data = os.walk(os.path.normcase('./'))

    flag = False

    for root, dirs, files in data: 

        for file in files:

            if (file.split('_')[0] == num and file.endswith('.jpg')):

                flag = True

                filename = os.path.join(root, file)

                try:

                    shutil.copyfile(filename, str(datetime.date.today())   slash   file)

                except:

                    pass

    if flag == True: print('OK==>No %s has been copied.' %num)

    elif flag == False: print('NG==>No %s does not exist.' %num)

    return

 if __name__ == '__main__':
        while True:

        slash = os.path.normcase('/')



        number = list(map(int, input("Enter multiple values: ").split()))
        # print(number)
        annotationNum=[]

        for num in number:
          # print(num)
          num=str(num)

          num=eval(num)

          annotationNum.append(num)
          # print(annotationNum)
        

        if annotationNum =='q':

            break

        try:

            os.makedirs(str(datetime.date.today()))

        except:

            pass



        for num in annotationNum:

          copyImage (num)
    ```

     output is
Enter multiple values:  965 966 968 4
NG==>No 965 does not exist.
NG==>No 966 does not exist.
NG==>No 968 does not exist.
NG==>No 4 does not exist.
Enter multiple values:  q

but I want the o/p
Enter multiple values:  965 966 968 4
OK==>No 965 has been copied.
OK==>No 966 has been copied.
OK==>No 968 has been copied.
NG==>No 4 does not exist.
Enter multiple values:  q

CodePudding user response:

Try using this script... I made some inline comments explaining any changes that I made. I wasnt sure what the 'q' conditional statement was for so you might want to put that back in if it was important.

import os
import shutil
import datetime

def copyImage (numbers, target):   # send in the full list of numbers to avoid 
                                   # multiple function calls
                                   # Also send in the target directory to avoid 
                                   # having to reconstruct it over and over
    data = os.walk(os.path.normcase('./')) 
    for root, _, files in data:
        for filename in files:
            # the next line splits the filename just as before but instead of 
            # comparing it to one number, it checks if it matches any of the
            # numbers in the number list
            if filename.split('_')[0] in numbers and filename.endswith('.jpg'):  
                fullpath = os.path.join(root, filename)
                try:
                    #  Use the target directory passed as a parameter to 
                    # construct the copy location
                    shutil.copyfile(fullpath, os.path.join(target, filename))
                    # output messages when they happen to avoid dealing with
                    #  flag variables
                    print(f"OK==>{fullpath} has been copied.")
                except:
                    print(f"NG==>{fullpath} failed to copy")

if __name__ == '__main__':
    target = str(datetime.date.today())  # construct the output target directory
    os.makedirs(target)                 # create the target directiory
    numbers = input("Enter multiple values: ").split()  # get input values and 
                                                        # split them into a 
                                                        # list but leave them 
                                                        # as strings since 
    copyImage(numbers, target)  # call function with the string list and 
                                # the target directory

CodePudding user response:

Here is a very simple way to do that!

First, to quit the while loop with 'q' we have to read users' inputs as str.

Next, by importing glob you can insert the names of the whole files (.jpg) to a list

Then, inside copyImage function, you need to change this to the folder name that you want to read your images from THE_NAME_OF_THE_FOLDER_TO_COPY_FROM

Now, using the power of List Comprehension we can do it by one line of code by loop in images and only do the copy when we find our intended num

Let me know if you need more explanation?

import shutil
import glob
import datetime
import os

def copyImage(num):
    images = glob.glob("THE_NAME_OF_THE_FOLDER_TO_COPY_FROM/*.jpg")
    # print(images)
    [shutil.copy(img, str(datetime.date.today())) for img in images if img.split('_')[0] == str(num) ]

if __name__ == '__main__':
    while True:
        numbers = list(map(str, input("Enter multiple values: ").split()))
        # print(numbers)

        if 'q' in numbers:
            print("Exit")
            break

        nums = [eval(number) for number in numbers]
        # print(num)

        try:
            os.makedirs(str(datetime.date.today()))
        except:
            pass    

        for n in nums:
            copyImage(n)
  • Related