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

Question:

My Folder Structure looks like this:

- 95000
- 95002
- 95009
- AR_95000.pdf
- AR_95002.pdf
- AR_95009.pdf
- BS_95000.pdf
- BS_95002.pdf
- BS_95009.pdf

[Note 95000, 95002, 95009 are folders]


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

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

Asked By: Drp RD

||

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.rpartition("_")[-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:

Answered By: Tomerikoo