如果文件夹不存在,Python 会创建一个文件夹列表

标签 python

如果文件夹不存在,我正在尝试创建文件夹列表。

我想遍历目录列表并创建它们,但每次都检查目录是否存在。

这是我的代码:

# 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/

相关文章:

python - C++ 和 Python 之间/中的区别

python - WAF——合并静态库

python - 如何在 Sublime Text 3 上安装 pandas

python - 如何在 Python 3.7 中正确地 requests.put

Python SARIMA 模型自动使用 CPU 的所有核心。如何?

python - 如何在 1D 和 nD 数组之间广播以获得 (1+n)D 数组输出?

python - 为什么 'python'和 `py`指向不同的用户站点

python - 处理不同数量的返回变量

python - 为第一行中的多列插入 0 的逻辑 - Pandas

python - 如何使用 alpha channel 给 png 图像着色?