3

I'm trying to create directories only if they don't exist using Python.

If the directory doesn't exist the script runs fine. But if it's already there I get an error that says:

An error has occurred: [WinError 183] Cannot create a file when that file already exists: '..\\..\\source_files\\aws_accounts_list'
Traceback (most recent call last):
  File ".\aws_ec2_list_instances.py", line 781, in <module>
    main()
  File ".\aws_ec2_list_instances.py", line 654, in main
    mongo_export_to_file(interactive, aws_account, aws_account_number)
  File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\ec2_mongo.py", line 292, in mongo_export_to_file
    create_directories()
  File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\ec2_mongo.py", line 117, in create_directories
    os.makedirs(source_files_path)
  File "C:\Users\tdun0002\AppData\Local\Programs\Python\Python38-32\lib\os.py", line 223, in makedirs
    mkdir(name, mode)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: '..\\..\\source_files\\aws_accounts_list'

This is my code:

def create_directories():
    ## Set source and output file directories
    source_files_path = os.path.join('..', '..', 'source_files', 'aws_accounts_list')

    # Create output files directory
    try:
        os.makedirs(source_files_path)
    except OSError as e:
        print(f"An error has occurred: {e}")
        raise

I want the exception to allow the script to continue if it encounters an error like this. How can I do that?

1
  • Have you tried adding an if statement to check if the path exists first? Or catch and ignore FileExistsError? Commented Jan 7, 2021 at 19:38

3 Answers 3

9

From Python 3.4, with pathlib this becomes quite an easy task using Path.mkdir:

from pathlib import Path

def create_directories():
    ## Set source and output file directories
    source_files_path = Path('..', '..', 'source_files', 'aws_accounts_list')

    # Create output files directory
    source_files_oath.mkdir(parents=True, exist_ok=True)

If you insist on os, then makedirs has another argument since Python 3.2 - exist_ok, which is:

If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists.

So just change to:

os.makedirs(source_files_path, exist_ok=True)
Sign up to request clarification or add additional context in comments.

Comments

3

Just don't reraise the error

# Create output files directory
try:
    os.makedirs(source_files_path)
except OSError as e:
    print(f"An error has occurred. Continuing anyways: {e}")

But we don't actually want to skip all OS errors, only if the file doesn't exist, so a better solution would be:

# Create output files directory
try:
    os.makedirs(source_files_path)
except FileExistsError as e:
    print('File already exists')
    return False
except OSError as e:
    print(f"An error has occurred: {e}")
    raise

Comments

1

As Tomerikoo suggested, You can also use os.path.exists

import os

if not os.path.exists(source_files_path):
    try:
        os.makedirs(source_files_path)
    except OSError as e:
        print(f"An error has occurred: {e}")
        raise

I leave this below as reference, as it may be suited for other situations similar.

You can make a check with os.path.isdir in case of a Directory:

import os

if not os.path.isdir(source_files_path):
    try:
        os.makedirs(source_files_path)
    except OSError as e:
        print(f"An error has occurred: {e}")
        raise

Or, you can use os.path.isfile in case of a file path:

import os

if not os.path.isfile(source_files_path):
    try:
        os.makedirs(source_files_path)
    except OSError as e:
        print(f"An error has occurred: {e}")
        raise

2 Comments

I'm still confused why the second part is necessary as the OP is creating a directory, and for the first part believe that exists makes more sense
Thanks, the one using os.path.exists(source_files_path) works. I couldn't get the ones using isdir working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.