Skip to main content
 首页 » 编程设计

python之如何删除具有多个扩展名的文件

2025年05月04日11oomusou

以下代码不起作用,而且过于冗长和冗余。修复它的最佳方法是什么?

if os.path.exists('*.obj'): 
    os.remove('*.obj') 
if os.path.exists('*.dll'): 
    os.remove('*.dll') 
if os.path.exists('*.exe'): 
    os.remove('*.exe') 
if os.path.exists('*.manifest'): 
    os.remove('*.manifest') 
if os.path.exists('*.pch'): 
    os.remove('*.pch') 
if os.path.exists('*.lib'): 
    os.remove('*.lib') 
if os.path.exists('*.rsp'): 
    os.remove('*.rsp') 
if os.path.exists('Makefile'): 
    os.remove('Makefile') 

请您参考如下方法:

os.remove , os.path.exists接受文件路径,而不是模式。

使用 os.listdir ,您不需要检查文件是否存在。

import os 
 
exts = ('.obj', '.dll', '.exe', '.manifest', '.pch', '.lib', '.rsp') 
for fn in os.listdir('.'): 
    if fn.lower().endswith(exts) or fn == 'Makefile': 
        os.remove(fn) 

str.endswith接受元组;可用于检查扩展:

>>> 'file.exe'.endswith(('.obj', '.dll', '.exe', '.manifest')) 
True 
>>> 'file.com'.endswith(('.obj', '.dll', '.exe', '.manifest')) 
False 

使用 set :

# set literal 
exts = {'.obj', '.dll', '.exe', '.manifest', '.pch', '.lib', '.rsp'} 
for fn in os.listdir('.'): 
    if os.path.splitext(fn)[-1].lower() in exts or fn == 'Makefile': 
        os.remove(fn)