I'm trying to get Python to read exactly how many pages are in a .TIF and I've modified some code from some help I got yesterday. I've gotten Python to read the .TIF file, and output the pages, however it only reads the first .TIF file it can find. I need it to go through all the .TIF files in the same location.

I was wondering how can I make it so that once it is done counting, it will continue to the next file until it is completely done.

Here is what I have so far

import os

from PIL import Image

count = 0

i = 0

tiffs_path = "c:\\tiftest"

for filename in os.listdir("c:\\tiftest"):

if filename.endswith(".TIF"):

img = Image.open(filename)

while True:

try:

img.seek(count)

print(filename)

print(count)

except EOFError:

break

count += 1

print(count)

解决方案

You can use Image.n_frames to find the number of frames in a TIFF. It was added in Pillow 2.9.0.

For example, with Pillow 4.2.1:

Python 2.7.13 (default, Dec 18 2016, 07:03:39)

[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> from PIL import Image

>>> img = Image.open("multipage.tiff")

>>> img.n_frames

3

>>>

So, something like this:

import os

from PIL import Image

count = 0

i = 0

tiffs_path = "c:\\tiftest"

for filename in os.listdir("c:\\tiftest"):

if filename.endswith(".TIF"):

img = Image.open(filename)

print(filename)

print(img.n_frames)

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐