python 使用python搜索jpeg文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2584589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 01:00:29  来源:igfitidea点击:

Search jpeg files using python

pythonsearchfile

提问by Nims

My requirement is to search for jpeg images files in a directory using python script and list the file names. Can anyone help me on how to identify jpeg images files.

我的要求是使用 python 脚本在目录中搜索 jpeg 图像文件并列出文件名。任何人都可以帮助我了解如何识别 jpeg 图像文件。

Thanks in advance...

提前致谢...

回答by Anurag Uniyal

If you need to search a single folder non-recursively you can simply do

如果您需要以非递归方式搜索单个文件夹,您可以简单地执行

>>> import glob
>>> glob.glob("D:\bluetooth\*.jpg")
['D:\bluetooth\Image1475.jpg',  'D:\bluetooth\Image1514.jpg']

Read more about globhere, you use do unix like wildcard searches e.g.

在此处阅读有关glob 的更多信息,您可以像使用通配符搜索一样使用 unix,例如

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']

回答by cryo

If you want to scan subfolders:

如果要扫描子文件夹:

import os

for root, subdirs, files in os.walk(DIRECTORY):
    for file in files:
        if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg'):
             print os.path.join(root, file)

Otherwise, using one of the other glob functions in the other answers, or this:

否则,在其他答案中使用其他 glob 函数之一,或者:

import os

for f in os.listdir(DIRECTORY):
    if os.path.splitext(f)[1].lower() in ('.jpg', '.jpeg'):
        print os.path.join(DIRECTORY, f)

should work OK.

应该可以正常工作。

回答by Ignacio Vazquez-Abrams

Use the magicmodule to get the MIME type, and look for image/jpeg.

使用magic模块获取 MIME 类型,然后查找image/jpeg.

回答by ghostdog74

import os
path=os.path.join("/home","mypath","to_search")
for r,d,f in os.walk(path):
     for files in f:
           if files[-3:].lower()=='jpg' of files[-4:].lower() =="jpeg":
                print "found: ",os.path.join(r,files)

回答by Frederik

If you want to determine the image format by file contents, you can use the Python Imaging Library:

如果要通过文件内容确定图像格式,可以使用Python Imaging Library

import Image
try:
    img = Image.open('maybe_jpeg_file')
    print img.format # Will return 'JPEG' for JPEG files.
except IOError:
    print "Not an image file or unreadable."