'How do I write file names to a new folder with an added prefix?
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)
Solution 1:[1]
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)
Solution 2:[2]
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)
Solution 3:[3]
Was able to alter the name using the replace() function.
Important for "batch\" double backward 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)
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 | Tilman De Lanversin |
| Solution 2 | Albert Winestein |
| Solution 3 |
