2017-10-19 25 views
0
a = os.listdir('.') 

a = ['60598-2-1.pdf', 'pdfsorter.py'] 

当我尝试使用这个:a.count("pdf")它返回0,它只适用于完整的文本。鉴于从os.listdir('。')返回,我如何计算扩展.pdf出现的次数?

实施例:

a.count("pdf") returns 0 

a.count("60598-2-1.pdf") returns 1 

解决方案:

https://stackoverflow.com/a/46832438/8641804 
+0

'count'通过返回值出现的次数。它不搜索部分字符串 – Wondercricket

+3

你有没有考虑过使用glob.glob('*。pdf')'? –

回答

2
a = ['60598-2-1.pdf', 'pdfsorter.py'] 
count = sum(1 for item in a if item.endswith('.pdf')) 
+0

这工作出来谢谢! – sapocacona

+0

@sapocacona np :) – galaxyan

0
import glob  
count = len(glob.glob("*.pdf")) # will gives you the count of pdf files in the cwd.