我正在试图使用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
如果脚本遇到像这样的错误,我希望异常能够让脚本继续执行。我该怎么做?
FileExistsError
错误吗? - OneCricketeer