zuzu
zuzu

Reputation: 15

Sorting file based on filename match with folder Python

im looking to write a script in Python than helps me sort file base one file name and create a dicrectory for the name if it not exist.

For example: I have 4 file in a folder named Unsorted

111-iam.txt

111-how.txt

110-uare.txt

110-uok.txt

I want to create a folder name 111 to keep all the file name 111-xxx.txt and folder name 110 to keep all file name 110-xxx.txt

I want it to check if the folder already there move the file in that folder, if not then create a new folder.

It worked for the first run, but if i have new file in Unsorted folder name started with 111 or 110 it show errors. The error is os.mkdir(full_path) FileExistsError: [Errno 17] File exists: '/home/pi/Desktop/Sorted/111' Here is my code.

Thanks you guys in advance

import os
import shutil

srcpath = "/home/pi/Desktop/Unsorted"
srcfiles = os.listdir(srcpath)

destpath = "/home/pi/Desktop/Sorted"

# extract the ten letters from filenames and filter out duplicates
destdirs = list(set([filename[0:2] 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:2]:
            move(filename, full_path)

Upvotes: 1

Views: 3468

Answers (1)

Alex Taylor
Alex Taylor

Reputation: 8813

os.path.isdir(path) will:

Return True if path is an existing directory.

So you could change your directory creation method to be:

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

Alternatively, ask forgiveness not permission:

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

Upvotes: 1

Related Questions