【问题标题】:Python deletion of files - "Currently being used by another process"Python删除文件-“当前正被另一个进程使用”
【发布时间】:2015-08-10 04:36:07
【问题描述】:

要求

我必须尝试创建一个程序来删除所有损坏的图像(以及小于 400x400 的图像)并将其余图像过滤成 10,000 个组。

问题

目前,当我尝试删除任何“损坏”的图像时,它表示该文件当前正在被另一个进程使用,每个错误如下:

该进程无法访问该文件,因为它正被另一个进程使用。

采取的步骤

我尝试了多种方法来释放文件,包括使用“后退踏板”策略,应用程序移动到下一个图像,然后后退踏板尝试删除该图像,但它仍然保持打开状态。 如果我在 Python 打开时尝试手动删除图像,它会很高兴地通过。

请看下面的代码:


def confirmIt():
#======== Confirm Selection and Move files to new sub-directory:
if not folderPath.get() == "":                          ## make sure not blank
    source = folderPath.get()                           ## set source path 
    size = 0
    broken = False

    for fname in os.listdir(source):
        if  fname.lower().endswith(extensions):
            imageName = source+"\\"+fname               ## set the source location of the image
            try: 
                img = Image.open(imageName)
                width, height = img.size                    ## get the dimensions
                size = width * height / 1000
                broken = False
                img.close()
            except IOError, e:
                broken = True
                img.close()

            if ( broken == True ):
                def handleRemoveReadonly(func, path, exc):
                    excvalue = exc[1]
                    if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
                        os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO)
                        func(path)
                    else:
                        raise
                try:
                    os.remove(imageName)                ## Remove all remaining images that don't match the preset requirements (<400 and is an image)

额外信息

请注意,我也在使用 GUI,因此“resultMessage”和类似的输出/输入字段就是出于这个原因。


编辑:

在与@Cyphase 反复讨论后,我确定了问题所在。下降的帖子是由于我为他编辑了带有回溯的 OP。我并不真正使用这个论坛,因为我通常不需要编码。此应用程序的更多主题可能会出现。谢谢。


【问题讨论】:

  • 您确定其他进程没有保持打开文件吗?另外,你为什么在 if 块中定义handleRemoveReadonly(),而你甚至不使用它?
  • 错误消息来自哪个语句,openrmdirremove
  • 请注意,即使另一个进程正在使用该文件,删除也应该在 POSIX 下工作。也许你应该考虑用你正在使用的任何操作系统来标记它(我猜是 windows)。
  • 看来你在微软下工作(我建议你使用os.path.join而不是source+"\\"+fname),我不知道解锁文件的方法(可能使用ctypes和正确的系统调用)但是你可以use a tool likeProcess Explorer from Sysinternals 一样查看锁定它们的进程并尝试解决问题。
  • CFNZ_Technie 和@Cyphase,我已经回滚了关于图片上传大小限制的编辑。这是一个单独的问题,应该作为单独的问题提出。

标签: python image file-handling


【解决方案1】:

您的问题是您正在修改底层文件系统(通过删除图像),然后遍历(旧)文件列表。

这就是您的循环尝试打开不再存在的图像的原因。

解决方法是先存储文件列表,然后循环遍历文件列表;而不是os.listdir() 的输出(将被缓存)。

您还应该排除代码的一些组成部分。试试这个版本:

from itertools import izip_longest

# https://docs.python.org/2/library/itertools.html
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def get_valid_images(image_path):
    extensions = ['*.jpg']
    return [f for f in os.listdir(image_path)
            if f.lower().endswith(extensions)]

def is_valid_image(image_path):
    try:
        img = Image.open(image_path)
        img.load()
        width, height = img.size
        img.close()
        return True
     except IOError as e:
        print(e)
        img.close()
        return None
     finally:
        img.close()
    return None

def confirmIt():
    # Confirm selection and move files to new sub-directory
    source = folderPath.get()  # set source path
    if not source:
        return False # If there is no source no point going
                     # head
    file_list = get_valid_images(source)
    valid_images = []
    for fname in file_list:
        image_dim = is_valid_image(os.path.join(source, fname))
        if image_dim:
            valid_images.append(source)

    # Now, group the resulting list in bunches for your move
    for dir_num, filenames in enumerate(grouper(valid_images, 5)):
        dest = os.path.join(source, str(dir_num))
        if not os.path.exists(dest):
            try:
                os.makedirs(dest)
            except OSError, e:
                print(e)
                continue # Skip this set, as we cannot make the dir
        for fname in filenames:
            shutil.move(fname, dest)
            print('Moving {}'.format(fname))

【讨论】:

  • Hi Buhan...谢谢你,我没有考虑到 os.listdir 以缓存模式存储这些。我会等着看 Cyphase 提出了什么,因为我们已经得出了最终的工作情况,如果你有任何意见可以添加到他的身上,那就太好了。
【解决方案2】:

经过多次反复,这段代码应该可以做你想做的事,除非有任何错误:)。给其他任何人;可能还会进行一些更改以消除任何问题。

from __future__ import print_function

import errno
import os

try:
    from itertools import zip_longest  # Python 3
except ImportError:  # Python 2
    from itertools import izip_longest as zip_longest  # Python 2

from PIL import Image

DEFAULT_IMAGE_EXTS = ('.jpg',)


# From the recipes section of the itertools documentation:
# https://docs.python.org/3/library/itertools.html#itertools-recipes
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


def makedirs(d):
    try:
        os.makedirs(d)
    except OSError as e:
        # If the file already exists, and is a directory
        if e.errno == errno.EEXIST and os.path.isdir(d):
            created = False
        # It's some other error, or the existing file is not a directory
        else:
            raise
    else:
        created = True

    return created


def get_valid_filenames(directory, extensions):
    for filename in os.listdir(directory):
        if filename.lower().endswith(extensions):
            yield filename


def get_corrupt_image_filenames(directory, extensions=DEFAULT_IMAGE_EXTS):
    for filename in get_valid_filenames(directory, extensions):
        image_path = os.path.join(directory, filename)
        try:
            with open(image_path, 'rb') as filehandle:
                Image.open(filehandle)
                # img = Image.open(filehandle)
                # img.load()  # I don't think this is needed, unless
                #               the corruption is not in the header.
        except IOError:
            yield filename


def confirm_it(directory, extensions, images_per_dir=5000):
    # Confirm selection and move files to new sub-directory
    if directory:
        for corrupt_file_name in get_corrupt_image_filenames(directory):
            os.remove(os.path.join(directory, corrupt_file_name))

        valid_images = get_valid_filenames(directory, extensions)
        grouped_image_file_names = grouper(valid_images, images_per_dir)
        for subdir, image_filenames in enumerate(grouped_image_file_names):
            for filename in image_filenames:
                from_path = os.path.join(directory, filename)
                to_dir = os.path.join(directory, str(subdir))
                to_path = os.path.join(to_dir, filename)

                makedirs(to_dir)

                os.rename(from_path, to_path)


def confirm_it_wrapper():
    confirm_it(directory=folderPath.get(), extensions=extensions)

使用confirm_it_wrapper 代替confirm_it 作为tkinter Button 点击的回调。

【讨论】:

  • @CFNZ_Techie,应该已经删除了损坏的文件,除非您要删除该代码。
  • 我将很快创建一个新问题,并为您提供答案。谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 2012-10-27
相关资源
最近更新 更多