Skip to content

seek of closed file #1630

@v-python

Description

@v-python

I wanted to calculate a histogram of a multi-page TIFF file.

        im = Image.open( fn )
        colors = im.getcolors( im.width * im.height )
        if args.hist:
            for cnt, col in colors:
                allcolors[ col ] += cnt
            for iz in range( 1, im.n_frames ):
                im.seek( iz )
                colors = im.getcolors( im.width * im.height )
                for cnt, col in colors:
                    allcolors[ col ] += cnt

The above code would fail on the seek, with "seek of closed file" error. I tried first to add the extra open operation below just before the seek. It helped some, but not in every case.

        im = Image.open( fn )
        colors = im.getcolors( im.width * im.height )
        if args.hist:
            for cnt, col in colors:
                allcolors[ col ] += cnt
            for iz in range( 1, im.n_frames ):
                im = Image.open( fn ) # does getcolors implicitly close????
                                      # without the open, get "seek of closed
                                      # file" error on line below.
                im.seek( iz )
                colors = im.getcolors( im.width * im.height )
                for cnt, col in colors:
                    allcolors[ col ] += cnt

Randomly (or maybe experience based) guessing, I then tried hoisting the reference to n_frames out of the loop, as below. That seemed to make it reliable across a number of test cases that failed otherwise.

        im = Image.open( fn )
        imgcnt = im.n_frames
        colors = im.getcolors( im.width * im.height )
        if args.hist:
            for cnt, col in colors:
                allcolors[ col ] += cnt
            for iz in range( 1, imgcnt ):
                im = Image.open( fn ) # does getcolors implicitly close????
                                      # without the open, get "seek of closed
                                      # file" error on line below.
                im.seek( iz )
                colors = im.getcolors( im.width * im.height )
                for cnt, col in colors:
                    allcolors[ col ] += cnt

With this solution in hand, I tried removing the extra open inside the loop, but some failures recurred when I did so. So this last code is my "production solution" for now, but it is not at all clear why the initial code attempt at the top produces errors.

Pillow 3.0.0, Python 3.5.0, Windows 10.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions