sdavis891
sdavis891

Reputation: 101

Python Move Files Based On Name

To give credit, the code I am currently working with is from this response by cji, here.

I am trying to recursively pull all files from the source folder, and move them into folders from the file names first-five characters 0:5

My Code Below:

import os
import shutil

srcpath = "SOURCE"
srcfiles = os.listdir(srcpath)

destpath = "DESTINATION"

# extract the three letters from filenames and filter out duplicates
destdirs = list(set([filename[0:5] for filename in srcfiles]))


def create(dirname, destpath):
    full_path = os.path.join(destpath, dirname)
    os.mkdir(full_path)
    return full_path

def move(filename, dirpath):
    shutil.move(os.path.join(srcpath, filename)
                ,dirpath)

# create destination directories and store their names along with full paths
targets = [(folder, create(folder, destpath)) for folder in destdirs]

for dirname, full_path in targets:
    for filename in srcfiles:
        if dirname == filename[0:5]:
            move(filename, full_path)

Now, changing srcfiles = os.listdir(srcpath) and destdirs = list(set([filename[0:5] for filename in srcfiles])) with the code below gets me the paths in one variable and the first five characters of the file names in another.

srcfiles = []
destdirs = []

for root, subFolders, files in os.walk(srcpath):
    for file in files:
       srcfiles.append(os.path.join(root,file))
    for name in files:
       destdirs.append(list(set([name[0:5] for file in srcfiles])))

How would I go about modifying the original code to use this... Or if someone has a better idea on how I would go about doing this. Thanks.

Upvotes: 2

Views: 12918

Answers (1)

tjohnson
tjohnson

Reputation: 1077

I can't really test it very easily, but I think this code should work:

import os
import shutil

srcpath = "SOURCE"
destpath = "DESTINATION"

for root, subFolders, files in os.walk(srcpath):
    for file in files:
        subFolder = os.path.join(destpath, file[:5])
        if not os.path.isdir(subFolder):
            os.makedirs(subFolder)
        shutil.move(os.path.join(root, file), subFolder)

Upvotes: 5

Related Questions