【发布时间】:2014-06-10 09:35:25
【问题描述】:
我有一个 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)
输出如下:
转换图片:image1.tga
转换图像失败:/TEST/TGA/image1.tga 错误:无法识别图像文件
无法移动图像:image1.png 错误:[Errno 2] 没有这样的文件或目录:'/TEST/TGA/image1.png'
如果我在运行 python 脚本之前将 tga 文件复制到了 TGA 文件夹,一切正常,图片被转换并移动到其他目录,没有任何错误。
【问题讨论】:
-
外部工具是复制还是移动文件?
-
它复制了那个。我无法改变它的行为。我想我将不得不将失败的存储在一些列表中以供进一步检查。
-
NP,我只是想确认一下,因为复制的行为与移动不同。
-
在阅读完所有 cmets 后,我决定不删除源文件以防转换过程中出现异常,并在 while 循环中引入一些休眠秒数。现在我从 PIL 库中获取信息,例如: > Failed convert image: /TEST/TGA/image1.tga with error: image file is truncated (1006 bytes not processing) 但经过几次尝试后,文件最终被完全复制并进行了转换。谢谢大家的cmets!