strExtension允许两种格式

2024-10-02 18:28:06 发布

您现在位置:Python中文网/ 问答频道 /正文

如何允许对strExtension使用.pdf和.html等格式。 如果我改为strExtension=“*”,脚本将不起作用。 如何使用这两种格式?pdf和html?你知道吗

# extension of files
strExtension = ".pdf" 
# for each file in source directory
for file in os.listdir(sourceDir):
    # if file ends with extension
if file.endswith(strExtension):

Tags: ofin脚本sourceforifpdfhtml
3条回答

这对我有用。谢谢你的快速帮助。非常感谢你们。。。你知道吗

# extension of files
strExtension1 = ".pdf"
strExtension2 = ".html" 
# for each file in source directory
for file in os.listdir(sourceDir):
# if file ends with extension
if file.endswith(strExtension1) or file.endswith(strExtension2):

str.endswith()不支持通配符。但是,它支持元组,因此您可以执行以下操作:

extensions = (".html", ".pdf")
if file.endswith(extensions):
    # do stuff

只需测试两种情况:

if file.endswith(strExtension1) or file.endswith(strExtension2):

或者像乔恩·克莱门茨在下面评论的那样:

if file.endswith((strExtension1,strExtension2)):

相关问题 更多 >