Skip to main content
 首页 » 编程设计

python之文件存在于 os.listdir 但无法访问,因为它仍在被复制

2025年05月04日10insus

我有一个 python 脚本,其中 while(1) 循环使用 os.listdir 在特定文件夹中查找图像文件。 如果检测到任何受支持的格式,则使用 PIL 库将其转换为 PNG。 有时其他一些应用程序会将一些文件 (5MB) 复制到该目录,这需要一些时间。 问题是 os.listdir 在复制过程的最开始检测到每个文件的存在,但不幸的是,这些文件在复制完全完成之前不可用。

在复制完成之前打开一个文件不会抛出任何异常并且使用 os.access(path, os.R_OK) 检查对文件的访问也是可以的。

您是否知道如何确保 os.listdir 报告的所有文件都可用,因此在我的情况下已完全复制?

import time 
import os 
import shutil 
import Image 
 
#list of image formats supported for conversion 
supported_formats = ['bmp', 'tga'] 
output_format = 'png' 
output_prefix = 'prefix_' 
 
 
def find_and_convert_images(search_path, destination_path, output_img_prefix, new_img_format): 
    for img_file in os.listdir(search_path): 
        if img_file[-3:] in supported_formats: 
            print("Converting image: " + str(img_file)) 
            convert_image(os.path.join(search_path, img_file), new_img_format) 
            converted_img_name = img_file[:-3] + new_img_format 
            new_img_name = output_img_prefix + img_file[:-3] + new_img_format 
            if not os.path.isdir(destination_path): 
                os.makedirs(destination_path) 
            try: 
                shutil.move(os.path.join(search_path, converted_img_name), os.path.join(destination_path, new_img_name)) 
            except Exception, error: 
                print("Failed to move image: " + converted_img_name + " with error: " + str(error)) 
 
 
def convert_image(img_file, new_img_format): 
    try: 
        img = Image.open(img_file) 
        img.save(img_file[:-3] + new_img_format) 
        del img 
    except Exception, error: 
        print("Failed convert image: " + img_file + " with error: " + str(error)) 
    try: 
        os.remove(img_file) 
    except Exception, error: 
        print("Failed to remove image: " + img_file + " with error: " + str(error)) 
 
 
def main(): 
    images_directory = os.path.join(os.getcwd(), 'TGA') 
    converted_directory = os.path.join(images_directory, 'output') 
    while 1: 
        find_and_convert_images(images_directory, converted_directory, output_prefix, output_format) 

输出如下:

Converting image: image1.tga

Failed convert image: /TEST/TGA/image1.tga with error: cannot identify image file

Failed to move image: image1.png with error: [Errno 2] No such file or directory: '/TEST/TGA/image1.png'

如果我在运行 python 脚本之前将 tga 文件复制到 TGA 文件夹,一切正常,并且图片被转换并移动到其他目录,没有任何错误。

请您参考如下方法:

您可能需要保留一份未通过测试的文件列表,并在一段时间后再次检查它们,如果它们再次失败(或达到一定次数),您可以将它们标记为它们下次总是会失败并忽略它们。