2

while(1)ループが特定のフォルダー内の画像ファイルを検索する Python スクリプトがあります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] No such file or directory: '/TEST/TGA/image1.png'

Pythonスクリプトを実行する前にTGAファイルをTGAフォルダーにコピーした場合、すべて問題なく、写真は変換され、エラーなしで他のディレクトリに移動されます。

4

3 に答える 3

0

「不完全な」ファイルは検出できません。特定のファイル タイプでは、不完全なデータでも変換が成功する場合があります。

ファイルをコピーするプロセスを用意し、代わりにファイルを所定の場所に移動します。同じファイルシステムでは、ファイルの移動はアトミックです。たとえば、完全なデータが新しい場所に移動されます。それは単なる名前変更操作です。

同じディレクトリ内でも移動できます。スクリプトが無視するファイル名を使用してから、完成したコピーを所定の位置に移動 (名前を変更)します。

于 2014-06-10T09:45:09.567 に答える