Python创建目录错误当该文件已经存在时无法创建文件

blu*_*ndr 1 python

仅当目录不存在时,我才尝试使用 Python 创建目录。

如果该目录不存在,则脚本运行良好。但如果它已经存在,我会收到一个错误消息:

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'
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

我希望异常允许脚本在遇到这样的错误时继续。我怎样才能做到这一点?

Tom*_*koo 6

从 Python 3.4 开始,使用pathlib以下命令变得非常简单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)
Run Code Online (Sandbox Code Playgroud)

如果您坚持os,那么makedirs自 Python 3.2 - 以来还有另一个论点exist_ok,即:

如果exist_okFalse(默认值),如果目标目录已经存在,则会引发FileExistsError

所以只需更改为:

os.makedirs(source_files_path, exist_ok=True)
Run Code Online (Sandbox Code Playgroud)