H.Tang
H.Tang

Reputation: 103

Python - How to handle folder creation if folder already exists

def copy_excel():

    srcpath = "C:\\Aloha"           #where the excel files are located
    srcfiles = os.listdir(srcpath)  #sets srcfiles as list of file names in the source path folder
    destpath = "C:\\"               #destination where the folders will be created
    destdir = list(set([filename[19:22] for filename in srcfiles])) #extract three digits from filename to use for folder creation (i.e 505, 508, 517,...)

    #function to handle folder creation
    def create(dirname, destpath):
            full_path = os.path.join(destpath, dirname)
            if os.path.exists(full_path):
                    pass
            else:
                    os.mkdir(full_path)
            return full_path

    #function to handle moving files to appropriate folders
    def move(filename, dirpath):
            shutil.move(os.path.join(srcpath, filename), dirpath)

    #creates the folders with three digits as folder name by calling the create function above
    targets = [(folder, create(folder, destpath)) for folder in destdir]
    #handles moving files to appropriate folders if the three digits in file name matches the created folder
    for dirname, full_path in targets:
            for filename in srcfiles:
                    if dirname == filename[19:22]:
                            move(filename, full_path)
                    else:
                            pass

I am somewhat new to Python so please bear with me! I was able to find this code block on this site and tailored it to my specific use case. The code works well for creating the specified folders and dropping the files into the corresponding folders. However, when I run the code again for new files that are dropped into the "C:\\Aloha" I get a Error 183: Cannot create a file when that file already exists. In this case, the folder already exists because it was previously created when the script was run the first time.

The code errors out when targets attempts to create folders that already exist. My question is, what is the logic to handle folders that already exists and to ignore the error and just move the files to the corresponding folders? The script should only create folders if they are not already there.

Any help would be greatly appreciated! I have attempted try/except and nesting if/else statements as well as os.path.isdir(path) to check to see if the directory exists but I haven't had any luck. I apologize for any of the comments that are wrong, I am still learning Python logic as I build this script out.

Upvotes: 10

Views: 18970

Answers (3)

Marc Dix
Marc Dix

Reputation: 1959

Another option I just came by...

try:
    os.mkdir(path)
except FileExistsError:
    pass

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

You could use os.makedirs which not only will create cascading directories such that for instance C:\foo\bar\qux will create foo, bar and qux in case they do not exist, but you can also set the exist_ok=True such that no error is thrown if the directory exists.

So:

os.makedirs(full_path,exist_ok=True)

Upvotes: 31

Derlin
Derlin

Reputation: 9881

In case you want to throw an error or stop the processing if the directory exists, you can use os.path.exists(full_path) before mkdir.

Upvotes: 3

Related Questions