Home > front end >  How do I write file names to a new folder with an added prefix?
How do I write file names to a new folder with an added prefix?

Time:03-12

I'm trying to take a dir like ["cats.jpg", "dogs.jpg", "stars.jpg"] and resize them to 100x100 pixels and output the edited files into a new directory with the prefix "resized_" i.e ["resized_cats.jpg", "resized_dogs.jpg", "resized_stars.jpg"].

At the moment I'm getting the new directory but no files are being written to it.

batch =  glob.glob("files/batch/*.jpg")

for file in batch:
    img = cv2.imread(file,1)
    resize = cv2.resize(img, (100,100))
    
    if not os.path.exists("files/batchOut"):
        os.makedirs("files/batchOut")

    cv2.imwrite(f"files/batchOut/resized_{file}", resize)

CodePudding user response:

Was able to alter the name using the replace() function. Important for "batch\" double forward slashes are required i.e. "batch\\"

batch =  glob.glob("files/batch/*.jpg")

for file in batch:
    img = cv2.imread(file,1)
    resize = cv2.resize(img, (100,100))
    
    if not os.path.exists("files/batchOut"):
        os.makedirs("files/batchOut")

    cv2.imwrite("files/batchOut/resized_"   file.replace("files/batch\\", "" )   ".jpg", resize)

CodePudding user response:

You can use os.path.basename to isolate the file name from your path string like this:

batch =  glob.glob("files/batch/*.jpg")

for file in batch:
    img = cv2.imread(file,1)
    resize = cv2.resize(img, (100,100))

    if not os.path.exists("files/batchOut"):
        os.makedirs("files/batchOut")

    file_name = os.path.basename(file)
    cv2.imwrite(f"files/batchOut/resized_{file_name}", resize)

CodePudding user response:

You may find this to be a more robust approach. You certainly only want to call makedirs once:

import os
from glob import glob
import cv2
import sys

source_directory = '<your source directory>'
target_directory = '<your target directory>'
pattern = '*.jpg'
prefix = 'resized_'
dims = (100, 100)

os.makedirs(target_directory, exist_ok=True)

for filename in glob(os.path.join(source_directory, pattern)):
    try:
        img = cv2.imread(filename, cv2.IMREAD_COLOR)
        newfile = f'{prefix}{os.path.basename(filename)}'
        newfilepath = os.path.join(target_directory, newfile)
        cv2.imwrite(newfilepath, cv2.resize(img, dims))
    except Exception as e:
        print(f'Failed to process {filename} due to {e}', file=sys.stderr)
  • Related