舒蒂尔。快走不删除源文件

2024-10-01 13:44:46 发布

您现在位置:Python中文网/ 问答频道 /正文

新来的Python人。我已经编写了一个相当简单的脚本,从照片和视频中提取创建日期元数据,并将它们移动到基于年和月的新文件夹中。我使用PIL作为图片,hachoir用于视频元数据。在

在大多数情况下,在我真正使用之前,我一直在使用它舒蒂尔。快走. 在这一点上,所有的jpg移动到新的文件夹很好。但是所有的视频都被复制了。原始文件保留在源文件夹中。在

我的假设是,我在脚本期间调用的某个进程仍在访问视频文件,并且不允许将其删除。有人能告诉我我出什么事了吗?我怎样才能发布这些视频文件来移动?在

=========================

import os.path, time, sys, shutil
from PIL import Image
from PIL.ExifTags import TAGS
from hachoir_core.error import HachoirError
from hachoir_core.cmd_line import unicodeFilename
from hachoir_parser import createParser
from hachoir_core.tools import makePrintable
from hachoir_metadata import extractMetadata
from hachoir_core.i18n import getTerminalCharset


def get_field (exif,field) :
  for (k,v) in exif.iteritems():
     if TAGS.get(k) == field:
        return v



for picture in os.listdir(os.getcwd()):

    if picture.endswith(".jpg") or picture.endswith(".JPG"):
        print picture
        rawMetadata = Image.open(picture)._getexif()
        datetime = get_field(rawMetadata, 'DateTime')
        datedict = {'year' : datetime[0:4], 'month' : datetime[5:7]}
        target = datedict['year']+'-'+ datedict['month']

        if not os.path.isdir(target):
            newdir = os.mkdir(target)
        if picture not in target:
            shutil.move(picture, target)


    if picture.endswith('.mov') or picture.endswith('.MOV') or \
         picture.endswith('mp4') or picture.endswith('.MP4'):

        picture, realname = unicodeFilename(picture), picture
        parser = createParser(picture, realname)
        rawMetadata = extractMetadata(parser)
        text = rawMetadata.exportPlaintext()
        datedict = {'year' : text[4][17:21], 'month' : text[4][22:24]}

        target = datedict['year']+'-'+ datedict['month']

        dest = os.path.join(target, picture)

        if not os.path.isdir(target):
          newdir = os.mkdir(target)

        if picture not in target:
            try:
                shutil.move(picture, dest)
            except WindowsError:
                pass

Tags: orpathinfromcoreimportfieldtarget
2条回答

in运算符表示项是在集合中(例如,列表中的元素)还是字符串是其他字符串的子字符串。它不知道字符串变量target是目录的名称,也不知道如何检查目录以查看文件是否在其中。相反,请使用:

if os.path.exists(dest):

如果没有一个像样的错误代码,很难判断到底是什么失败了。在您的except块中使用此选项可获得更多答案:

except WindowsError as e:
    print("There was an error copying {picture} to {target}".format(
        picture=picture,target=target))
    print("The error thrown was {e}".format
        (e=e))
    print("{picture} exists? {exist}".format(
        picture=picture, exist=os.exists(picture))
    print("{target} exists? {exist}".format(
        target=target,exist=os.exists(target))

注意,logging模块对于这样的错误可以说很多。不过,这超出了这个问题的范围。在

相关问题 更多 >