在Pillow中打开后移动图像时出现PermissionError

时间:2015-11-07 05:31:42

标签: python pillow

我有一个小脚本,用于计算多页TIFF中的页面计数,然后再将它们移动到另一个驱动器;但是在用Pillow打开图像后我是否明确关闭了图像,在随后尝试移动文件时我不断收到PermissionError:

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'

我已经尝试了以下每种方法,以及我已经忘记的其他变体:

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)

即使在不同的功能中包含每个不同的操作也没有区别。

我哪里错了?

我在Win7和Win10上使用Pillow v3.0.0和Python v3.4.2。

1 个答案:

答案 0 :(得分:-1)

您在这里面临的是Sharing Violation Error

要避免您应该使用Win32file.move文件获取更多信息,您应go to

win32file.MoveFile(source, target)

将完成这项工作。