Search code examples
pythondirectorydirectory-structurefile-structure

Python Cut/Copy paste file from folder to another folder


I have bunch of PDFs that are reports generated by system named 00002755, 00002758, 00002760 ...so on etc.

I already have Folders named exactly as above 00002755, 00002758, 00002760 ...so on etc.

What i want to achieve is cut the PDF file "00002755.pdf" and paste it inside Folder named "00002755"

My Folder at the moment looks like this:

  1. Folder - 00002755
  2. Folder - 00002758
  3. Folder - 00002760
  4. 00002755.pdf
  5. 00002758.pdf
  6. 00002760.pdf

The conclusion would be when I run the python script all the pdfs will go into their respective folders.


Solution

  • It can be accomplished in different ways with different modules, here I'll use os only which should be fine and quite fast too (never benchmarked this with huge amounts of files/dirs, feel free to do so if you need it for your task)

    import os
    
    
    curr_dir = os.path.dirname(os.path.realpath(__file__))  # Get current abspath based on your py file name
    
    for i in [f.name for f in os.scandir(curr_dir) if f.is_dir()]:  # Iterate through the dirs
        for j in [f.name for f in os.scandir(curr_dir) if f.is_file()]:  # Iterate through the files
            if i == j.split(".pdf")[0]:  # If both match each other, move the file with os.rename
                os.rename(f"{curr_dir}\\{j}", f"{curr_dir}\\{i}\\{j}")