2016-05-23 60 views
1

有沒有辦法這樣的一組文件擴展名類型,而不是所有的冗餘OR條件?或條件Python

for file in os.listdir(source_directory): 
    if file.endswith(".xlsx") or file.endswith(".xls") or file.endswith(".xlsm") or file.endswith(".xlsb"): 

因此,像

if file.endswith(".xlsx","xls","xlsm","xlsb"): 
+4

你接近:'file.endswith(( 「XLS」, 「XLSM」, 「XLSB」), 「XLSX」):' – vaultah

回答

4

報價official docs強調礦):

str.endswith(suffix[, start[, end]])

返回True如果字符串結尾 與特異性ied後綴,否則返回False後綴也可以是 後綴元組尋找。使用可選啓動,在該位置開始測試 。選擇結束時,停止在該位置進行比較。

版本2.5中已更改:接受元組作爲後綴。

所以,正確的用法是:

for file in os.listdir(source_directory): 
    if file.endswith((".xlsx","xls","xlsm","xlsb")): 
     pass # do something 
+0

我不能接受你的答案,但我會。謝謝 – Rodger