Python代码,提取扩展
可能重复:
In python, how can I check if a filename ends in '.html' or '_files'?Python代码,提取扩展
import os
path = '/Users/Marjan/Documents/Nothing/Costco'
print path
names = os.listdir(path)
print len(names)
for name in names:
print name
这是我一直在使用的代码,它列出了这一类终端中的所有名称。这个文件中有几个文件名(Costco)没有.html和_files。我需要挑选出来,唯一的问题是它有超过2500个文件名。需要关于代码的帮助,该代码将搜索此路径并挑选出所有不以.html或_files结尾的文件名。谢谢你们
for name in names:
if filename.endswith('.html') or filename.endswith('_files'):
continue
#do stuff
通常,如果你需要一个文件的扩展名os.path.splitext()
会更合适,但在这种情况下endswith()
是完全没有问题。
这可以压缩到'filename.endswith(('。html','_ files'))'。 – DSM
比ThiefMaster的建议短一些:
for name in [x for x in names if not x.endswith(('.html', '_files'))]:
# do stuff
为什么不使用生成器表达式而不是列表理解?你忘了' – ThiefMaster
@ThiefMaster'中的外部名字:不确定,我总是发现生成器有点奇怪,但我想它会节省一些内存。更正了错误,谢谢。 – Junuxx
'[name for name in names ...]',而不是'[name in name ...]' –
这就是你一直在问关于这个问题,几个小时的第三个问题。停止对此提出新的问题。 – Daenyth