如果文件夹不存在,我正在尝试创建文件夹列表。
我想遍历目录列表并创建它们,但每次都检查目录是否存在。
这是我的代码:
# Create output subdirectories
folders = ['csv','excel','html', 'json']
for folder in folders:
if not os.path.exists(output_files_path,folder):
os.mkdir(os.path.join(output_files_path,folder))
这是我遇到的错误:
Traceback (most recent call last):
File ".\aws_ec2_list_instances.py", line 767, in <module>
main()
File ".\aws_ec2_list_instances.py", line 708, 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 279, 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 122, in create_directories
if not os.path.exists(output_files_path,folder):
TypeError: exists() takes 1 positional argument but 2 were given
我怎样才能正确地做到这一点?
最佳答案
你可以使用os.makedirs
有一个关键字选项exist_ok
,如果设置为true,如果文件夹已经存在则不会覆盖它。
makedirs
还可以在一次调用中递归地创建多个子目录。在我看来,这似乎让您的工作轻松多了。
如果您正在寻找如何正确调用 os.path.exists
:
您好像错过了 join
调用:
os.path.exists(os.path.join(output_files_path,folder))
关于如果文件夹不存在,Python 会创建一个文件夹列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65621176/