簡體   English   中英

我正在編寫 python 腳本,通過將一行中的多個輸入復制到另一個文件夾,從一個文件夾復制某些多個圖像文件 (.jpg)

[英]I am writing the python script for copy the certain multiple image files (.jpg)from one folder by giving multiple input in one line to another folder

我有大的 jpeg 文件數據集。文件名是這樣的 965_0000000005_0000000001_20211105153826.jpg 965_0000000005_0000000002_20211105153826.jpg。 .

966_0000000005_0000000001_20211105153832.jpg。 .

967_…………. .

依此類推...我想讓 python 腳本通過根據 965、966、988、.、.,.. 給多個輸入文件名來復制文件,然后它將復制到新文件夾。 我正在嘗試使用以下代碼將多個圖像文件從一個文件夾復制到另一個文件夾

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

嘗試使用此腳本...我做了一些內聯評論,解釋了我所做的任何更改。 我不確定'q'條件語句的用途,所以如果它很重要,您可能想把它放回去。

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
    unused = numbers[:]
    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
            part = filename.split('_')[0]
            if part in numbers and filename.endswith('.jpg'):
                if part in unused:
                    unused.remove(part)
                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==>No {fullpath} has been copied.")
                except:
                    print(f"NG==>No {part} failed to copy")
    for number in unused:
        print(f"NG==>No {number} does not exist")

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
    numbers = [i.strip() for i in numbers if i]
    copyImage(numbers, target)  # call function with the string list and
                                # the target directory

這是一個非常簡單的方法!

首先,要使用'q'退出 while 循環,我們必須將用戶的輸入讀取為str

接下來,通過導入glob ,您可以將整個文件 (.jpg) 的名稱插入到列表中

然后,在copyImage function 中,您需要將其更改為要從THE_NAME_OF_THE_FOLDER_TO_COPY_FROM讀取圖像的文件夾名稱

現在,利用List Comprehension的強大功能,我們可以通過在圖像中循環的一行代碼來完成它,並且只在找到我們想要的num時才進行復制

如果您需要更多解釋,請告訴我?

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('/')[1].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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM