[英]How do I ignore a file that already exists?
这就是我所拥有的:
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
。 有人可以告诉我我应该在代码中更改什么以使其以我想要的方式工作吗?
你出错的地方是第 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)
使用新的(在 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
为真,FileExistsError
异常将被忽略,但前提是最后一个路径组件不是现有的非目录文件。
使用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')
您的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:第 3 行: if os.path.exists(file_path) == True
== True
不是必需的,因为存在函数返回一个布尔值。 if os.path.exists(file_path):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.