這就是我所擁有的:
import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
file_path = rf'../database/{names}'
if os.path.exists(file_path) == True:
print('name folders exists')
else:
for name in names:
os.makedirs(os.path.join('../database', name))
names如果它們不存在,我希望代碼為串列中的每個名稱創建檔案夾,name folder exists如果它們已經存在則列印。但我一直FileExistsError在最后一行得到一個。有人可以告訴我我應該在代碼中更改什么以使其以我想要的方式作業嗎?
uj5u.com熱心網友回復:
你出錯的地方是第 3 行。這條線沒有做你認為它會做的事情:
file_path = rf'../database/{names}'
它創建一個字串,其中所有名稱都添加為串列。相反,您可以嘗試這樣的事情:
import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
base_path = '../database'
for name in names:
full_path = os.path.join(base_path, name)
if os.path.exists(full_path):
print('name folders exists')
else:
os.mkdir(full_path)
uj5u.com熱心網友回復:
使用新的(在 Python 3.4-3.5 中引入,所以現在不是新的)Pathlib模塊而不是os.path:
from pathlib import Path
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
BASE_PATH = Path('../database')
for name in names:
(BASE_PATH / name).mkdir(exist_ok=True)
從以下檔案:pathlib.Path.mkdir
如果
exist_ok為 true,FileExistsError則將忽略例外,但前提是最后一個路徑組件不是現有的非目錄檔案。
uj5u.com熱心網友回復:
使用try/except塊來捕獲并忽略這些錯誤。
例如
try:
os.makedirs(os.path.join('../database', name))
except FileExistsError:
pass
你甚至可以像這樣重寫你的代碼:
import os
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
for name in names:
try:
os.makedirs(os.path.join('../database', name))
except FileExistsError:
print('name folders exists')
uj5u.com熱心網友回復:
你的file_path變數是錯誤的。它../database/與您的串列連接。您串列中的所有元素。結果如下所示:
names = ['Abby','Betty','Bella','Peter','Jack','Sonya']
file_path = rf'../database/{names}'
print(file_path)
# ../database/['Abby', 'Betty', 'Bella', 'Peter', 'Jack', 'Sonya']
相反,這樣做:
# Import os define names
for name in names:
path = rf'../database/{name}'
if not os.path.exists(path):
os.mkdir(os.path.join(path))
PS:if os.path.exists(file_path) == True第3 行:== True不是必需的,因為存在函式回傳一個布林值。做就是了if os.path.exists(file_path):
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/493602.html
上一篇:如何獲取串列中的檔案路徑?
