1

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)
zuzu
  • 15
  • 1
  • 4
  • 1
    _it show errors_ - what errors did it show? Don't make us guess! This may be something we can solve at a glace without running the script. Make it easy for us to answer. – tdelaney Mar 22 '17 at 04:30
  • Very sorry for the missing information. The error is os.mkdir(full_path) FileExistsError: [Errno 17] File exists: '/home/pi/Desktop/Sorted/111' – zuzu Mar 22 '17 at 04:33

1 Answers1

1

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
Community
  • 1
  • 1
Alex Taylor
  • 8,343
  • 4
  • 25
  • 40