简体   繁体   English

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

[英]Python create a list of folders if it doesn't exist

I'm trying to create a list of folders if they don't exist.如果它们不存在,我正在尝试创建一个文件夹列表。

I want to iterate through a list of directories and create them, but check each time if the directory exists.我想遍历目录列表并创建它们,但每次检查目录是否存在。

This is my code:这是我的代码:

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

This is the error I'm getting:这是我得到的错误:

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

How can I do this correctly?我怎样才能正确地做到这一点?

You can use os.makedirs您可以使用os.makedirs

There is a keyword option exist_ok , if you set to true, will not overwrite it if the folder already exists.有一个关键字选项exist_ok ,如果您设置为 true,如果文件夹已经存在,则不会覆盖它。

makedirs can also create multiple subdirectories recursively in a single call. makedirs还可以在一次调用中递归地创建多个子目录。 This seems to make your job a lot easier in my opinion.在我看来,这似乎让你的工作轻松多了。

If you're looking for how to call os.path.exists properly:如果您正在寻找如何正确调用os.path.exists

It seems like you're missing a join call:您似乎错过了join通话:

os.path.exists(os.path.join(output_files_path,folder))

Just need to pass in the full path to os.path.exists instead of the path as two parameters.只需将完整路径传递给 os.path.exists 而不是路径作为两个参数。

for folder in folders:
    full_path = os.path.join(output_files_path,folder)
    if not os.path.exists(full_path):
        os.mkdir(full_path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM