我有一个 python 脚本,其中while(1)
循环在特定文件夹中查找带有os.listdir
. 如果检测到任何受支持的格式,则将其转换为PNG
带PIL
库。有时,其他一些应用程序会将一些文件 (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 文件夹,一切正常,图片将被转换并移动到其他目录,没有任何错误。