Home > database >  Move files to its corresponding folders
Move files to its corresponding folders

Time:10-06

How can I move every file to its corresponding folder? I managed to create a folder depending on the title of the file. Now I want to move every file to its folder.

My code:

import os 
directorio=list(os.listdir())

pdfs=[]

for i in directorio: 
  if i.endswith('.pdf'):
    pdfs.append(i)
  
#with this step we create different folders for each group of files 
for i in range(len(pdfs)):

  folder=pdfs[i].split('#')[1].split('.')[0]

  try:
    folder=os.mkdir(folder)
  except:
    pass

enter image description here

CodePudding user response:

Here's a cleaned up version of your original code which moves as well. Note that I have used pathlib.Path rather than the old os.path api.

from pathlib import Path

for pdf in Path(".").glob("*.pdf"):
    dir = pdf.parent / pdf.stem.split("#")[-1]
    dir.mkdir(exist_ok=True)
    pdf.rename(dir / pdf.name)

Changes:

  • use glob. But listdir and manual filtering also works
  • don't cast to list
  • move straight after making the dir, since that's what we want the dir for, and we know it at the moment!

exist_ok causes mkdir to continue if the directory is already present, rather than throwing an error.

  • Related