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

3

我正在试图使用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

如果脚本遇到像这样的错误,我希望异常能够让脚本继续执行。我该怎么做?


你试过先添加一个if语句来检查路径是否存在吗?或者捕获并忽略FileExistsError错误吗? - OneCricketeer
3个回答

9
从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,那么自Python 3.2起makedirs有另一个参数- exist_ok,它是:

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

所以只需要更改为:
os.makedirs(source_files_path, exist_ok=True)

2

只需不重新引发错误即可。

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

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

# 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

1

正如Tomerikoo所建议的那样,您还可以使用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

我将以下内容留作参考,因为它可能适用于其他类似的情况。

如果是目录,您可以使用os.path.isdir进行检查:

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

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

我仍然不明白为什么第二部分是必要的,因为原帖正在创建一个目录。对于第一部分,我认为exists更合理。 - Tomerikoo
谢谢,使用os.path.exists(source_files_path)的那个方法有效。我无法让使用isdir的那些方法起作用。 - bluethundr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接