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.
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:
Path.globPath.stemstr.rpartitionPath.renamePath.nameIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With