Python move files from current path to specific folder named like or similar to the file being moved

Viewed 5105

My Folder Structure looks like this:

  1. Folder 95000
  2. Folder 95002
  3. Folder 95009
  4. AR_95000.pdf
  5. AR_95002.pdf
  6. AR_95009.pdf
  7. BS_95000.pdf
  8. BS_95002.pdf
  9. BS_95009.pdf

[Note folder is named 95000, 95002 etc, the actual word 'folder' is not present in folder name, its just mentioned here for representation purpose.]


My goal is, move files "AR_95000.pdf" and "BS_95000.pdf" to folder named - "95000", then "AR_95002.pdf" and "BS_95002.pdf" to folder named - "95002"and so on.

The PDFs are reports generated by system and thus I can not control the naming of the same. Thanks!

1 Answers

Using pathlib this task becomes super easy:

from pathlib import Path

root = Path("/path/to/your/root/dir")

for file in root.glob("*.pdf"):
    folder_name = file.stem.rsplit("_", 1)[-1]
    file.rename(root / folder_name / file.name)

As you can see, one main advantage of pathlib over os/shutil (in this case) is the interface Path objects provide directly to os-like functions. This way the actual copying (rename()) is done directly as an instance method.


References:

Related