简体   繁体   English

Python:将文件夹中的所有文件转换为 JPG,但应仅考虑 JPG 和 PNG

[英]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.该代码将所有文件转换为.jpg,但它应该只为.png 和.jpg 执行此操作,而不是例如 for.gif。 So how can I ignore other files except PNG and JPG?那么如何忽略除 PNG 和 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:您可以向 select 添加额外的列表理解,仅包含dateien列表中的 jpg 和 png 文件:

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:您可以使用glob库:

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.一种用于 png 图像,一种用于 jpg 图像。

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.我所做的只是向listdir返回添加一个过滤器,它检查最后 4 个字符是否与列表中的扩展名之一相同。

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.使用 getcwd() 可能并不总是给您所需的结果,因为您无法确定脚本将从何处运行。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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