简体   繁体   中英

Python: Converting all files in a folder to JPG, but only JPG and PNG should be considered

The code transforms all files to.jpg but it should do this only for.png and.jpg, not for example for.gif. So how can I ignore other files except PNG and JPG?

import os, sys
from PIL import Image

size = 200, 200
root=os.getcwd()+"\\train"
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print(dirlist)

for ordner in dirlist:
    print(ordner)
    dateipfad=root+"\\"+ordner
    dateien = [ item for item in os.listdir(dateipfad)]
    print(dateien)
    for datei in dateien:
        print(datei)
        outfile = os.path.splitext(datei)[0] + "_resize.jpg"
        try:
            im = Image.open(dateipfad+"\\"+datei)
            im = im.resize(size)
            im.save(dateipfad+"\\"+outfile, "JPEG")

You can add an extra list comprehension, to select only the jpg and png files in your dateien list:

dateien = [ item for item in os.listdir(dateipfad)]
dateien = [ item for item in dateien if item[-3:] in ['jpg', 'png'] ]

and you can even combine both list comprehensions into a single line:

dateien = [ item for item in os.listdir(dateipfad) if item[-3:] in ['jpg', 'png'] ]

You can use glob library:

from glob import glob
files_list = [j for i in [glob('path/to/images/directory/'+e) for e in ['*jpg', '*png']] for j in i]

Or simply use:

files_list = [glob('path/to/images/directory/'+e) for e in ['*jpg', '*png']]

This will give you a list that contains two lists. One for png images and one for jpg images.

This should do the trick. All I did was add a filter to the listdir return which checks if the last 4 characters are the same as one of the extensions in the list.

dateien = [item for item in filter(lambda fn: fn[-4:].lower() in ['.png', '.jpg'], os.listdir(dateipfad))]

Using getcwd() may not always give you the result you need because you can't be sure where the script is going to be run from. OK for testing but maybe consider this:

import os
import glob

ROOT = os.path.expanduser('~') # this will equate to the user's HOME directory regardless of where the script is located

BASEDIR = os.path.join(ROOT, 'train', '*.*') # for cross-platform portability

for file in [F for F in glob.glob(BASEDIR) if F.lower().endswith('jpg') or F.lower().endswith('png')]:
    print(file) # process the file here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM