'Shutil can't move files with special characters

can't open/read file: check file path/integrity

so every time there's a special character in my file's name, i can't move the file. Shutil.Copy is not an option since I have too many files.

Is there another library or another solution to this?

def run():
    #resize
all_files = [f for f in listdir("E:\\Images\\path\\") if isfile(join("E:\\Images\\path\\", f))]
for file in all_files:
    try:
        im = cv2.imread("E:\\Images\\path\\" + file)
        width = im.shape[0]
        height = im.shape[1]

        ratio = width - height

        print(width, height)

        if abs(ratio) < 1000:
            shutil.move(f"E:\\Images\\path\\{file}", f"E:\\Images\\path\\Square\\{file}")
            
        elif width < height:
            shutil.move(f"E:\\Images\\path\\{file}", f"E:\\Images\\path\\Horizontal\\{file}")

        elif width > height:
            shutil.move(f"E:\\Images\\path\\{file}", f"E:\\Images\\path\\Vertical\\{file}")
    except:
        print('error')

run()



Solution 1:[1]

Please bear in mind that I have no way of testing this so caveat emptor

This approach greatly simplifies the pathname handling and will also emit a meaningful error message if anything goes wrong.

There is, however, an assumption that you're only interested in JPG files. If that's not right then you'll need to make some minor adjustments.

import glob
import os
import cv2
import shutil

BASE = 'E:\\Image\\path'

for file in glob.glob(os.path.join(BASE, '*.jpg')):
    try:
        im = cv2.imread(file)
        width = im.shape[0]
        height = im.shape[1]
        ratio = abs(width-height)
        if ratio < 1_000:
            target = 'Square'
        else:
            target = 'Horizontal' if width < height else 'Vertical'
        shutil.move(file, os.path.join(BASE, target, os.path.basename(file)))
    except Exception as e:
        print(f'Failed to process {file} due to {e}')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Albert Winestein