0

I have one folder contains a lot of folders(52 folders) named very complicated. Inside each of the folders, contains 80 folders and I want to open only 20 of them. Each 20 folders contains 12 images (some are dicom and others are jpeg). I want to select only one image and create a folder and save them as jpg.

Problem here is, 52 folders' names are complicated. 80 folders' have exactly same names for all 52 folders. (A1,...A20, B1, ..., B20, C1,...C20, D1,...,D20) Also, 12 images are (A1ori_0001, A1cha_0001,... something like that). another problem is those 12 images have same name for 52 folders.

Hope this question is understandable.

Dana An
  • 25
  • 5

2 Answers2

1

Without example code I can only do so much. But maybe this will point you in the right direction.

import glob, os
from PIL import Image
os.chdir("/mydir")
for file in glob.glob("*.jpeg"):
    if file.endswith(".jpeg"):
        img = Image.open(file)
        img.save('image.png')
Jortega
  • 3,616
  • 1
  • 18
  • 21
0

It seems to me then you have at least four problems:

  1. Trying to traverse to one of only 20 "special" folders. Your wording of the problem makes it ambiguous as to whether you mean 20 specific folders whose names you know, or 20 random folders. I'm going to assume the former.
  2. Finding any and all files in these folders that are images
  3. For a given folder from step #1, convert ONE of these images to a .jpg file.
  4. Move this converted file to a brand new folder.

For #1, granted, you could use os.walk() or glob to search a given directory and all its subdirectories for the files that you want. But that's going to return everything, which means you'd then have to whittle it down. Instead, if you already know the 20 folders, then it may make sense to start with a list of those, and then apply os.walk() on each of those individually to get their respective contents.

For #2, note that os.path.splitext(filename)[-1] returns the file extension (including the '.') of the file filename. So as you're traversing the directories and finding files, you can use this to check to see if the extension looks like the type of file you want to covert to .jpg (whatever that may be: .bmp, .png, whatever).

For #3, you can use Python's PIL module to convert a given file. For more information on how to do that, see this previous question.

Then #4 is just a matter of using a function like os.mkdir() to create the directory, and shutil.move() to move it.

Bill M.
  • 1,388
  • 1
  • 8
  • 16