Search code examples
pythoncopymove

Python shutil.move copies endlessly


I made a script that reads pdf-files from a src-folder, gets some info from the file and then renames the file and moves it to another location. This is done every 5 seconds.

Since the src and dest are on different disks I use shutil.move instead of os.rename.

Because src and dest are on a different disk shutil.move wil instead copy and delete the source file.

The script works fine, but sometimes there are problems with permissions in the source folder. This keeps the source file in the source folder and is copied endlessly because the source file can't get deleted.

How can I work around this? Since I don't keep the name of the original pdf-files I don't know how to solve this.

enter image description here


Solution

  • Have you considered keeping track of when you last moved files, and then only moving source files with later modification timestamps?

    You can call os.scandir() to list the source directory, getting a DirEntry info on each of its entries. For each entry, check entry.is_file() to see if it's a file, entry.name to see if it ends with '.pdf', and its entry.stat().st_mtime to see if it's newer than your last scan.

    You can still call shutil.copyfile() to copy each chosen file to the new name in the destination directory.