Home > Software design >  How to move files with similar filename into new folder in Python
How to move files with similar filename into new folder in Python

Time:09-22

I have a list of files like this in the images folder.

enter image description here

and How can I create a new folder if there are multiple files with a similar name and move those similar files to that folder?

I am new to python.

Here is my expectation:

enter image description here

CodePudding user response:

In this case you don't even need re:

from pathlib import Path
for fn in Path("Images").glob("*.jpg"):
    outdir = Path("Images") / "_".join(fn.stem.split("_")[:-1])
    outdir.mkdir(exist_ok=True)
    fn.rename(outdir / fn.name)

What's going on here?

input_img

Output: output_img

Please ignore file names extension. I create those just to test my code

  • Related