2012-06-03 67 views
-4

可能重複:
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結尾的文件名。謝謝你們

+1

這就是你一直在問關於這個問題,幾個小時的第三個問題。停止對此提出新的問題。 – Daenyth

回答

3
for name in names: 
    if filename.endswith('.html') or filename.endswith('_files'): 
     continue 
    #do stuff 

通常,如果你需要一個文件的擴展名os.path.splitext()會更合適,但在這種情況下endswith()是完全沒有問題。

+1

這可以壓縮到'filename.endswith(('。html','_ files'))'。 – DSM

0

比ThiefMaster的建議短一些:

for name in [x for x in names if not x.endswith(('.html', '_files'))]: 
    # do stuff 
+0

爲什麼不使用生成器表達式而不是列表理解?你忘了' – ThiefMaster

+0

@ThiefMaster'中的外部名字:不確定,我總是發現生成器有點奇怪,但我想它會節省一些內存。更正了錯誤,謝謝。 – Junuxx

+0

'[name for name in names ...]',而不是'[name in name ...]' –