首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python创建目录错误在文件已经存在时不能创建文件

Python创建目录错误在文件已经存在时不能创建文件
EN

Stack Overflow用户
提问于 2021-01-07 19:37:03
回答 3查看 4.5K关注 0票数 2

只有在使用Python不存在目录的情况下,我才试图创建目录。

如果目录不存在,则脚本运行良好。但是如果它已经存在了,我会发现一个错误,它说:

代码语言:javascript
运行
复制
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'

这是我的密码:

代码语言:javascript
运行
复制
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

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-01-07 19:46:38

在Python3.4中,使用pathlib使用Path.mkdir变得非常容易

代码语言:javascript
运行
复制
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在Python3.2-exist_ok之后还有另一个论点,即:

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

因此,只需更改为:

代码语言:javascript
运行
复制
os.makedirs(source_files_path, exist_ok=True)
票数 8
EN

Stack Overflow用户

发布于 2021-01-07 19:40:34

只是不要重蹈覆辙

代码语言:javascript
运行
复制
# Create output files directory
try:
    os.makedirs(source_files_path)
except OSError as e:
    print(f"An error has occurred. Continuing anyways: {e}")

但是,我们实际上不想跳过所有操作系统错误,只有当文件不存在时,更好的解决方案是:

代码语言:javascript
运行
复制
# 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
票数 2
EN

Stack Overflow用户

发布于 2021-01-07 19:41:59

正如Tomerikoo所建议的,您也可以使用os.path.exists

代码语言:javascript
运行
复制
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

我将此作为参考,因为它可能适合于其他类似的情况。

在出现目录时,可以使用os.path.isdir进行检查:

代码语言:javascript
运行
复制
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

或者,您可以在文件路径的情况下使用os.path.isfile

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65618858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档