Skip to content Skip to sidebar Skip to footer

Python Moving Files Based On Extensions?

How can I improve this python code. I want to add a list here which includes all the extension and with the help of the list, I want to search for 'src' directory for extensions an

Solution 1:

I would use a dict of locations and extensions, for example {'/home/xxx/Pictures': ['jpg','png','gif'], ...} Where I use the "keys" as destinations and the values are lists of extensions for each destination.

source = '/home/xxx/randomdir/'
mydict = {
    '/home/xxx/Pictures': ['jpg','png','gif'],
    '/home/xxx/Documents': ['doc','docx','pdf','xls']
}
for destination, extensions in mydict.items():
    for ext in extensions:
        for file in glob.glob(source + '*.' + ext):
            print(file)
            shutil.move(file, destination)

While Fabre's solution is good, you would have to repeat his double-loop solution for every destination folder, whereas here you have a triple-loop that does everything, as long as you give it a proper dict

Also a word of advice, if you write code that looks so repetitive, like yours do, be sure there is a way to make it simpler, either with a loop or a function that takes arguments.

Solution 2:

Another extensible solution

import os
import shutil

dir1 = "/home/xxxx/Software/"
dir2 = "/home/flyingpizza/Pictures/"

def moveto(dst):
    return lambda src: shutil.move(src, dst)

action = {
    'pdf': moveto(dir1),
    'docx': moveto(dir1),
    'exe': moveto(dir1),
    'jpg': moveto(dir2),
    'torrent': os.remove,
}

src_dir = '/home/xxxxx/Downloads'for file inos.listdir(src_dir):
    ext = os.path.splitext(file)[1][1:]
    if ext in action:
        action[ext](os.path.join(src_dir, file))

Solution 3:

with a double loop and generate the pattern using format:

for ext in ["docx","pdf","exe","jpg"]:
    for file in glob.glob('/home/xxxxx/Downloads/*.{}'.format(ext)):
        print (file)
        shutil.move(file,dest_dir)

Solution 4:

Copy the following code and save as ".py" in the same folder with the file you want to separate by extension, then run the python file.

from os import *
import shutil

def makeDir(DirectoryName):
    if path.exists(DirectoryName)==False: mkdir(DirectoryName)

def movefile(item):
    extName=path.splitext(item.name)[1][1:]
    try:
        if extName != '':
            makeDir(extName)
            shutil.move(item, extName)
        elif extName == '' and item.name[0][0]!='.':
            makeDir('NoExt')
            shutil.move(item, 'NoExt')
        else:
            makeDir('NoName')
            shutil.move(item, 'NoName')
    except:
        None

chdir(path.dirname(__file__))

for file in scandir(getcwd()):
    movefile(file) if path.isfile(file) and file.name != path.basename(__file__) else None

Post a Comment for "Python Moving Files Based On Extensions?"