只有在使用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
我希望异常允许脚本在遇到像这样的错误时继续运行。我怎么能这么做?
发布于 2021-01-07 19:46:38
在Python3.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
在Python3.2-exist_ok
之后还有另一个论点,即:
如果exist_ok是
False
(默认值),则如果目标目录已经存在,则会引发FileExistsError。
因此,只需更改为:
os.makedirs(source_files_path, exist_ok=True)
发布于 2021-01-07 19:40:34
只是不要重蹈覆辙
# 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
发布于 2021-01-07 19:41:59
正如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
https://stackoverflow.com/questions/65618858
复制相似问题