Home > Software design >  shutil.move() not working after reading object with pywin32
shutil.move() not working after reading object with pywin32

Time:01-27

I've got a script that is intended to sort my photo/video collection (Windows). The photos work fine as they are sortable by EXIF which is easily accessed.

Videos are harder because I have to get the file's "Media Creation Date" which is readable by only pywin32, to my understanding. However, once I've accessed the media creation date, shutil.move() does not work. It throws no error, it just runs indefinitely without progress until I manually kill the script:

Here's the snippet in question:

from datetime import datetime
import exifread
import os
from pathlib import Path
import shutil
from win32com.propsys import propsys, pscon

# get the file list, do stuff with photos, etc
# f is the file
# cr is the path root to which it will be moved

    elif str(f).lower().endswith(("mp4", "mov")):
        props = propsys.SHGetPropertyStoreFromParsingName(f)
        dt = props.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()
        year, month = str(dt.year), str(dt.month).zfill(2)
        new_fn = dt.strftime("%Y-%m-%d_%H%M%S")
        new_fn = f"{new_fn}{os.path.splitext(f)[1]}"
        move_path = os.path.join(cr, year, month, new_fn)
        print(f"SRC: {f}")
        print(f"DESTINATION: {move_path}")
        print("----------------------------------")
        shutil.move(f, move_path)

It prints the source correctly, and the destination correctly, but does not move the file. I have also tried os.rename() and os.replace() with the same result, which suggests that perhaps the propsys method still has a lock on the file? How do I free up this file for moving?

CodePudding user response:

Yes, propsys is blocking the file (you can check in Process Explorer), try just deleting it:

fpath = r'c:\temp\user\t\test.mp4'
move_path = r'c:\temp\user\t\test moved.mp4'
props = propsys.SHGetPropertyStoreFromParsingName(fpath)
print( props.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() )
del props
shutil.move(fpath , move_path)
  • Related