[英]Python create a list of folders if it doesn't exist
如果它們不存在,我正在嘗試創建一個文件夾列表。
我想遍歷目錄列表並創建它們,但每次檢查目錄是否存在。
這是我的代碼:
# 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))
只需將完整路徑傳遞給 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.