Python创建目录报错Cannot create a file when that file already exists

标签 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'

这是我的代码:

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

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

最佳答案

来自 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)

如果你坚持os,那么makedirs自 Python 3.2 以来还有另一个参数 - exist_ok,即:

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

所以只需更改为:

os.makedirs(source_files_path, exist_ok=True)

关于Python创建目录报错Cannot create a file when that file already exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65618858/

相关文章:

python - 如何删除一段 matplotlib 轴

python - Sphinx 文档模块属性

Python,最后一个元素剪切

python - 如何在特定级别为多索引列添加前缀?

python - 从字符串数组列表中获取值?

python - 如何在应用程序上运行命令并在 cloudfoundry 上获取退出代码

python - 替换Python中的出现

python - 如何在 Django 中用户未输入数据的情况下在 POST 请求中发送数据

python - 需要重新审视密码程序

Python Set Comprehension嵌套在Dict Comprehension中