Home > Software design >  How to save images with for-loop and list
How to save images with for-loop and list

Time:05-30

I have a folder with several subfolders. These contain different files. All files ending with "Red_Lines.png" I want to save in another directory (I work with Windows). My procedure so far looks like this:

Create a list with all Filenames:

import os
List = []

for root, Lists, files in os.walk("C:/Users/.../Old_Folder/"):
    for name in files:
        if name.endswith("Red_Lines.png"):
            List.append(name)

Create new List with complete Path and Filenames:

k = []
for filename in List:
    k.append(os.path.join("C:/Users/.../New_Folder", filename).replace("\\" , "/"))

Save Images finally

from PIL import Image
for i in k:
    img = Image.open(i)
    img.save(i) 

But now, i get the following Error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/.../New_Folder/123_Red_Lines.png'

The error message confuses me. Of course the file does not exist yet, I want to create it...

Thanks

CodePudding user response:

Why not just use command line "copy" to copy your files and not needing PIL module (comment #2 in the sample code). and another thing is, your code cannot find the file you are copying to (comment #1 in the sample code).

you can try this:

import os
List = []

for root, Lists, files in os.walk("C:/Users/.../Old_Folder/"):
    for name in files:
        if name.endswith("Red_Lines.png"):
            List.append(os.path.join(root, name)) # joining the root   name

destinationFile = "C:/Users/.../New_Folder"
for filename in List:
    os.system(f'copy "{filename}" "{destinationFile}"') # copy-command

CodePudding user response:

i think you try to open file that have not created in Image.open(i) where your i is the new path. The Image.open should refers to Old_Folder

  • Related