这是使用两种方法检查文件名是否包含任何扩展名的两个示例。
ext = ('.txt', '.py', '.docx', '.pdf') # tuple of extensions. filenames = [ ... ] # list of filename strings ends_matches = [ f for f in filenames if f.endswith(ext) ] # change ext to set for slightly better efficiency. split_matches = [ f for f in filenames if f.splitext()[1] in ext ] # may need to include .lower() for cases with capital extensions.
在这种情况下,取决于您的实际使用情况。如果您只想检查一个文件扩展名,则建议使用endswith
。
return filename.endswith(extension)