I want to move files that match the criteria in re.search to a different directory.

Asked 2 years ago, Updated 2 years ago, 41 views

I would like to move only the image with the name "1536_496" in the file name from one directory to another.
I tried writing the code, but I got the following error.
Could you advise me how to eliminate the error?

Also, even if I correct the above, I feel that the current code will not only move to the image that matches the conditions in the re.search, but also move to a different directory for each directory where the image is stored.If anyone knows what to do about that, please let me know.

error message

Error: Destination path'./NORMAL_resize_rename_10000/NORMAL_resize_rename_copy_10000' already exists

Actual Code

import glob
importos
import re
import shutil

# Move the image with "1536_496" in the saved name to a different folder

input_dir='./NORMAL_resize_rename_10000'# Source Directory
output_dir='./NORMAL_resize_rename_copy_10000'# Destination Directory

# If the output directory does not exist, create it.
os.madeirs(output_dir, exist_ok = True)

for path in glob.glob(input_dir+"/*.jpeg"):
    img=Image.open(path)# Load image from path
    match=re.search('1536_496', path)# input_dir+"/*.jpeg"
    if match:
        move(output_dir, input_dir)#Move the output_dir image to input_dir

python python3

2022-09-30 14:58

1 Answers

The re.search didn't work well, so I added it to the code I wrote when I got the size of the image in the directory as follows, and it worked.Sorry for the trouble.

import glob
importos
import cv2
import sys
import shutil

# The argument is the file path of the image.
# a function that reads an image and returns resolution information
default_resolution(filepath):

    img=cv2.imread(filepath)

    # Error termination if image file read fails
    if img is None:
        print("Failed to load image file.")
        sys.exit(1)

    # by color and gray scale
    iflen(img.shape) == 3:
        height, width, channels = img.shape [:3]
    else:
        height,width=img.shape [:2]
        channels = 1

    return width, height, channels

# Arguments are in the directory
# count the resolution of a file in a directory
def count_resol(directory):
    print(directory)
    files=glob.glob(directory)
    mov_dir='./NORMAL_resize_copy_100_1_0506'# Added
    os.madeirs(mov_dir, exist_ok=True)# Added
    d = {}
    for file in files:
        width, height, channels = get_resolution(file)
        info=str(width)+", "+str(height)+", "+str(channels)
        d. set default (info, 0)
        d[info]+=1
        if str(width) == 1536 and str(height) == 496:# added
            shutil.copy(file,'./NORMAL_resize_copy_100_1_0506/')# Added

    print(d)


2022-09-30 14:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.