Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python create directory error Cannot create a file when that file already exists

Tags:

python

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?

like image 497
bluethundr Avatar asked Mar 14 '26 09:03

bluethundr


1 Answers

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)
like image 142
Tomerikoo Avatar answered Mar 15 '26 22:03

Tomerikoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!