Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python创建目录错误无法在文件已存在时创建该文件_Python - Fatal编程技术网

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

Python创建目录错误无法在文件已存在时创建该文件,python,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_

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

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

只是不要重新确认错误

# 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

只是不要重蹈覆辙

# 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
根据建议,您还可以使用


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

对于目录,您可以使用进行检查:

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
或者,您可以在文件路径的情况下使用:

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
根据建议,您还可以使用


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

对于目录,您可以使用进行检查:

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
或者,您可以在文件路径的情况下使用:

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
从Python 3.4开始,通过使用以下工具,这将成为一项非常简单的任务:

从pathlib导入路径
def create_目录():
##设置源和输出文件目录
源文件路径=路径(“..”、“..”、“源文件”、“aws\U帐户列表”)
#创建输出文件目录
source\u files\u誓言.mkdir(parents=True,exist\u ok=True)

如果您坚持使用
os
,那么自Python 3.2-
存在以来还有另一个参数,即:

如果exist\u ok为
False
(默认值),则在以下情况下引发 目标目录已存在

因此,请改为:

os.makedirs(source_files_path, exist_ok=True)
从Python 3.4开始,通过使用以下工具,这将成为一项非常简单的任务:

从pathlib导入路径
def create_目录():
##设置源和输出文件目录
源文件路径=路径(“..”、“..”、“源文件”、“aws\U帐户列表”)
#创建输出文件目录
source\u files\u誓言.mkdir(parents=True,exist\u ok=True)

如果您坚持使用
os
,那么自Python 3.2-
存在以来还有另一个参数,即:

如果exist\u ok为
False
(默认值),则在以下情况下引发 目标目录已存在

因此,请改为:

os.makedirs(source_files_path, exist_ok=True)

您是否已尝试添加if语句以首先检查路径是否存在?或者捕获并忽略
文件existserror
?您是否尝试添加if语句来检查路径是否首先存在?或者捕获并忽略
fileexisterror
?我仍然不明白为什么第二部分是必需的,因为OP正在创建一个目录,而对于第一部分,我认为使用
os.path.exists(source\u files\u path)
的方法更合理。我无法让使用
isdir
的运行。我仍然不明白为什么第二部分是必需的,因为OP正在创建一个目录,而对于第一部分,我认为使用
os.path.exists(source\u files\u path)
的运行更合理。我无法使用isdir使这些文件正常工作。如果我尝试使用`#创建输出文件目录os.makedirs(source\u files\u path,exists\u ok=True)`我收到一个错误:
TypeError:makedirs()得到一个意外的关键字参数“exists\u ok”
@bluethundr抱歉,简单的输入错误。没有
s
ok很酷,谢谢。我会试试看。现在,我得到了:
os.mkdir(os.path.join(output\u files\u path,folder,exist\u ok=True))类型错误:join()得到了一个意外的关键字参数“exist\u ok”
这是我的代码:
os.makedirs(source\u files\u path,exist\u ok=True)
知道怎么了吗?现在开始工作了。谢谢你的帮助!如果我尝试使用`#Create output files directory os.makedirs(source\u files\u path,exists\u ok=True)`我得到一个错误:
TypeError:makedirs()得到一个意外的关键字参数“exists\u ok”
@bluethundr抱歉,简单的输入错误。没有
s
ok很酷,谢谢。我会试试看。现在,我得到了:
os.mkdir(os.path.join(output\u files\u path,folder,exist\u ok=True))类型错误:join()得到了一个意外的关键字参数“exist\u ok”
这是我的代码:
os.makedirs(source\u files\u path,exist\u ok=True)
知道怎么了吗?现在开始工作了。谢谢你的帮助!