Home > Mobile >  how to move files in different sub-directories?
how to move files in different sub-directories?

Time:01-14

i have a directory with files with different extensions, i have to move these files in their folder (creating them) inside the "files directory", i write that but i need help (first project please be gentle)

'''import os
import shutil

os.makedirs("C:\\FileOrganizer\\FileOrganizer\\Files\\Images")
os.makedirs("C:\\FileOrganizer\\FileOrganizer\\Files\\Text")
os.makedirs("C:\\FileOrganizer\\FileOrganizer\\Files\\Mp3")

src_fldr = "C:\\FileOrganizer\\FileOrganizer\\Files"
fldr_img ="C:\\FileOrganizer\\FileOrganizer\\Files\\Images"
fldr_txt = "C:\\FileOrganizer\\FileOrganizer\\Files\\Text"
fldr_mp3 = "C:\\FileOrganizer\\FileOrganizer\\Files\\Mp3"

for file in os.listdir(src_fldr): 
filename = os.fsdecode(file)
    if filename.endswith(".txt", ".otd"):
       shutil.move(src_fldr, fldr_txt)
    elif filename.endswith(".jpeg", ".jpg", ".png"):
         shutil.move(src_fldr, fldr_img)
    elif filename.endswith(".mp3"):
         shutil.move(src_fldr, fldr_mp3)
    else: 
         pass'''

CodePudding user response:

You should move the source file instead of the source folder into the destination folder

for file in os.listdir(src_fldr): 
    filename = os.fsdecode(file) # remove me
    if filename.endswith(".txt", ".otd"):
        shutil.move(file, fldr_txt)
    elif filename.endswith(".jpeg", ".jpg", ".png"):
        shutil.move(file, fldr_img)
    elif filename.endswith(".mp3"):
        shutil.move(file, fldr_mp3)
    else: 
        pass

also, I think you should remove the os.fsdecode entire line and change use file directly

if file.endswith(".txt", ".otd"):
  •  Tags:  
  • Related