如何忽略已经存在的文件?
这就是我所拥有的:
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))
我希望代码在name
列表中创建每个名称的文件夹,如果它们不存在并打印名称文件夹,则存在
(如果已经存在)。但是我一直在最后一行中获得file existersError
。有人可以告诉我我应该在代码中更改什么以使其以我想要的方式工作?
This is what I have:
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))
I want the code to create the folders for each name in names
list if they do not exist and print name folder exists
if they already exist. But I keep getting a FileExistsError
on the last line. Can someone tell me what I should change in the code to get it to work in the way I want it to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您出错的地方是第3行。此行不执行您认为会做的事情:
它创建一个字符串,其中所有名称添加为列表。
相反,您可以尝试这样的事情:
Where you went wrong was line 3. This line doesn't do what you think it would do:
It creates a single string with all the names added as a list.
Instead, you can try something like this:
使用新的(在python 3.4-3.5中引入,现在不是新的) pathlib 模块而不是
os.path
:从
pathlib.path.mkdir
的文档:Use the new (introduced in Python 3.4-3.5, so not that new now) Pathlib module instead of
os.path
:From the documentation of
pathlib.Path.mkdir
:使用
尝试/除外
块来捕获并忽略这些错误。例如,
您甚至可以这样重写您的代码:
use a
try/except
block to catch and ignore these errors.eg
You could even rewrite your code like this:
您的
file_path
变量是错误的。它与您的列表相连../数据库/
。您列表的所有元素。结果看起来像这样:相反,请这样做:
ps:第3行:
如果OS.Path.exists(file_path)== true
== true true true
不是必需的,因为存在函数返回布尔值。只需执行如果OS.Path.exists(file_path):
Your
file_path
variable is wrong. It concatenate../database/
with your list. All elements of your list. The result looks like this:Instead, do like this:
PS: line 3:
if os.path.exists(file_path) == True
The== True
is not necessary because the exists function returns a boolean. Just doif os.path.exists(file_path):
示例,只是查看忽略文件或单词的工作方式:
Example, just to see how IGNORE files or words works: