Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | None | 0 0
  1. import os
  2. import shutil
  3.  
  4. #The Path of the directory to be sorted
  5. path = '/path/to/directory'
  6. #This populates a list with the filenames in the directory
  7. list_ = os.listdir(path)
  8.  
  9. #Traverses every file
  10. for file_ in list_:
  11.     name,ext = os.path.splitext(file_)
  12.     #Stores the extension type
  13.     ext = ext[1:]
  14.     #If it is directory, it forces the next iteration
  15.     if ext == '':
  16.         continue
  17.     #If a directory with the name 'ext' exists, it moves the file to that directory
  18.     if os.path.exists(path+'/'+ext):
  19.        shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_)
  20.     #If the directory does not exist, it creates a new directory
  21.     else:
  22.         os.makedirs(path+'/'+ext)
  23.         shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement