Python Image.open()无法识别正则表达式

时间:2016-04-23 03:34:31

标签: python regex

from PIL import Image
image1 = "Image_I0000_F1_Filter 1_1A_health_2014-05-20_11.05.33.483.tiff"
image2 = "*F1*.tiff"
im1 = Image.open(image1)
im2 = Image.open(image2)

试图打开相同的图像。 im1打开没有问题,但im2显示IOError:[Errno 2]没有这样的文件或目录:' * F1 * .tiff'。

也试过

image2 = r"*F1*.tiff"
im2 = Image.open(image2)

image2 = "*F1*.tiff"
im2 = Image.open(open(image2,'rb'))

既不起作用。

1 个答案:

答案 0 :(得分:1)

PIL.Image.open没有全局匹配。 The documentation建议

  

您可以使用字符串(表示文件名)或文件对象作为文件参数

值得注意的是不包括全局匹配。

Python使用glob模块进行全局匹配。

from PIL import Image

import glob

filenames = glob.glob("*F1*.tiff")
# gives a list of matches, in this case most likely
# # ["Image_I0000_F1_Filter 1_1A_health_2014-05-20_11.05.33.483.tiff"]
if filenames:
    filename = filenames[0]
else:
    # what do we do if there's no such file? I guess pass the empty string
    # to Image and let it deal with it
    filename = ""
    # or maybe directly...
    raise FileNotFoundError

im1 = Image.open(filename)