2

我有一个 python 脚本,其中while(1)循环在特定文件夹中查找带有os.listdir. 如果检测到任何受支持的格式,则将其转换为PNGPIL库。有时,其他一些应用程序会将一些文件 (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)

输出如下:

转换图像:image1.tga

转换图像失败:/TEST/TGA/image1.tga 错误:无法识别图像文件

无法移动图像:image1.png 错误:[Errno 2] 没有这样的文件或目录:'/TEST/TGA/image1.png'

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

4

3 回答 3

1

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

于 2014-06-10T09:47:21.230 回答
0

恕我直言,没有文件完整性的概念。

您可以创建一个运行 1[sec] 的简单循环,并检查文件大小是否有任何变化,如果可以跳过此文件。

您可以使用以下内容获取文件大小:

import os
file_size = os.path.getsize("/path_to_file/my_file.jpg")
于 2014-06-10T09:43:58.730 回答
0

您无法检测到“不完整”文件;对于某些文件类型的转换甚至可能在不完整的数据上成功。

有复制文件的过程,而是将文件移动到位。在同一个文件系统上,移动文件是原子的;例如,完整的数据将被移动到新位置。这只是一个重命名操作。

您甚至可以在同一目录中进行移动;使用脚本忽略的文件名,然后将完成的副本移动(重命名)到位。

于 2014-06-10T09:45:09.567 回答