我正在编写一个 Python 脚本,它遍历一个目录并收集某些文件,但是我想排除一些文件,它们都以相同的方式开始。
示例代码:
for name in files:
if name != "doc1.html" and name != "doc2.html" and name != "doc3.html":
print name
假设目录中有 10000 个 HTML 文件,所有文件都以 'doc'
开头。排除它们的最简单方法是什么?
抱歉,我是 Python 的新手,我知道这可能是基础知识。
提前致谢。
最佳答案
if not name.startswith('doc'):
print name
如果您有更多要排除的前缀,您甚至可以这样做:
if not name.startswith(('prefix', 'another', 'yetanother')):
print name
startswith可以接受前缀元组。
关于python - 在 python 中,如果文件以一组特定的字母开头,我如何从循环中排除文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2193710/