如何在for循环中不显示特定值?

2024-09-27 02:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python将所有文件名列在一个列表中

这是我目前的代码:

import os
from os.path import isfile, join

test = 'C:/Users/Nelly/Desktop/test folder'

one = [f for f in os.listdir(test) if isfile(join(test, f))]

print(one)

上面的代码返回所有文件名的列表。我有一个不希望返回的特定值,即Thumbs.db。不确定是什么,但不应该在列表中

我如何排除它


Tags: 文件path代码fromtestimport列表os
1条回答
网友
1楼 · 发布于 2024-09-27 02:22:57

只需在您的理解中添加一个附加条件:

one = [f for f in os.listdir(test) if isfile(join(test, f)) and not f == 'Thumbs.db']

或者,如果您只想在扩展上进行筛选:

one = [f for f in os.listdir(test) if isfile(join(test, f)) and not f.endswith('.db')]

相关问题 更多 >

    热门问题