PermissionError when moving image after being opened in Pillow
Question: I have a small script for tallying pagecounts in multi-page TIFFs before
moving them to another drive; but whether or not I explicitly close the images
after opening them with Pillow, I keep getting a PermissionError when
subsequently trying to move the file:

    
    
    Traceback (most recent call last):
      File "C:\Python34\lib\shutil.py", line 522, in move
        os.rename(src, real_dst)
    PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'c:/users/barry/desktop/bort.tiff' ->  'c:/users/barry/desktop/bart.tiff'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "<pyshell#75>", line 1, in <module>
        shutil.move('c:/users/barry/desktop/bort.tiff', 'c:/users/barry/desktop/bart.tiff')
      File "C:\Python34\lib\shutil.py", line 535, in move
        os.unlink(src)
    PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'c:/users/barry/desktop/bort.tiff'
    

I've tried each of the following methods, plus other variations I've already
forgotten:

    
    
    import os
    import shutil
    from PIL import Image
    
    name1 = 'C:/Users/Barry/Desktop/bort.tiff' # This file exists.
    name2 = 'C:/Users/Barry/Desktop/bart.tiff' # This file doesn't.
    
    # Attempt 1:
    img = Image.open(name1)
    pgs = img.n_frames
    img.close()               # Tried both with and without this in each attempt.
    shutil.move(name1, name2) # Tried both shutil.move and os.rename
    
    # Attempt 2:
    with Image.open(name1) as img:
        pgs = img.n_frames
        img.close()           
    shutil.move(name1, name2)
    
    # Attempt 3:
    with Image.open(name1) as img:
        pgs = img.n_frames
    img.close()               
    shutil.move(name1, name2) 
    
    # Attempt 4:
    with open(name1, 'rb') as file:
        with Image.open(file) as img:
            pgs = img.n_frames
    img.close()               
    shutil.move(name1, name2)
    

Even containing each distinct operation in different functions made no
difference.

Where am I going wrong?

I'm using Pillow v3.0.0 with Python v3.4.2 on both Win7 and Win10.


Answer: What you are facing over here is [Sharing Violation
Error](https://mail.python.org/pipermail/python-win32/2011-August/011738.html)

to avoid that you should use Win32file.movefile for further information you
should [go
to](https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=8&cad=rja&uact=8&ved=0CEYQFjAHahUKEwiM_fDr0_3IAhVHk3IKHY4NBrM&url=https%3A%2F%2Fmsdn.microsoft.com%2Fen-
us%2Flibrary%2Fwindows%2Fdesktop%2Faa365239\(v%3Dvs.85\).aspx&usg=AFQjCNFzN2v3_4rAKs7M37jkzjGqAuZrPw&sig2=k24rYo93ne19Lm2_1Ub-
Fw&bvm=bv.106923889,d.d24)

    
    
    win32file.MoveFile(source, target)
    

will do the work.

