Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 382
Drp RD Avatar asked Sep 12 '25 15:09

Drp RD


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.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.glob
  • Path.stem
  • str.rpartition
  • Path.rename
  • path concatenation
  • Path.name
like image 147
Tomerikoo Avatar answered Sep 15 '25 04:09

Tomerikoo