簡體   English   中英

shutil.move不會刪除源文件

[英]shutil.move doesn't delete source files

新手Python家伙在這里。 我已經寫了一個我認為非常簡單的腳本,可以從照片和視頻中提取創建日期元數據,然后根據年份和月份將它們移動到新文件夾中。 我將PIL用於圖片,將hachoir用於視頻元數據。

在大多數情況下,直到我實際使用shutil.move為止,它都能正常工作。 那時,所有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

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模塊可以說很多。 但是,這超出了這個問題的范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM