或条件Python

或条件Python,python,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"): 引用(强调我的): str.e

有没有一种方法可以使某些类型的文件扩展名类型取代所有冗余或条件

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"):
引用(强调我的):

str.endswith(后缀[,开始[,结束]])

如果字符串结束,则返回
True
使用指定的后缀,否则返回
False
后缀也可以是 要查找的后缀元组。使用可选的开始,测试开始 在那个位置。使用可选结束,停止在该位置进行比较

在版本2.5中更改:接受元组作为后缀

因此,正确的用法是:

for file in os.listdir(source_directory):
    if file.endswith((".xlsx","xls","xlsm","xlsb")):
        pass  # do something
引用(强调我的):

str.endswith(后缀[,开始[,结束]])

如果字符串结束,则返回
True
使用指定的后缀,否则返回
False
后缀也可以是 要查找的后缀元组。使用可选的开始,测试开始 在那个位置。使用可选结束,停止在该位置进行比较

在版本2.5中更改:接受元组作为后缀

因此,正确的用法是:

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

你很接近:
file.endswith((“.xlsx”、“xls”、“xlsm”、“xlsb”):
你很接近:
file.endswith((“.xlsx”、“xls”、“xlsm”、“xlsb”):
我还不能接受你的答案,但我会的。谢谢你我还不能接受你的回答,但我会的。非常感谢。