2014-01-25 123 views
1

以下代碼不起作用,且過於冗長且冗長。解決問題的最佳方法是什麼?如何刪除具有多個擴展名的文件

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') 
+1

也許對http://codereview.stackexchange.com – embert

+3

後寫一個函數? – unlimit

+2

因爲當'os.path.exists'和'os.remove'開始使用glob模式時? –

回答

4

我想使用glob

from glob import glob 

patterns = ('*.obj', '*.dll', '*.exe', '*.manifest', '*.pch', '*.lib', '*.rsp', 'Makefile') 
for p in patterns: 
    for f in glob(p): 
     os.remove(f) 
7

os.removeos.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) 
1

你可以使用正則表達式匹配文件名稱。下面根據擴展名和任何特定的文件名生成需要的文件。編譯完成後,只需要將編譯後的match()方法應用於每個候選文件名,以確定是否刪除它。

import os 
import re 

dirpath = './testfiles' 
exts = ('obj', 'dll', 'exe', 'manifest', 'pch', 'lib', 'rsp') 
fns = ('Makefile',) 

pattern = '|'.join(r'.+\.{}$'.format(re.escape(ext)) for ext in exts) 
if fns: pattern += '|' + '|'.join(re.escape(fn) for fn in fns) 
fnpat = re.compile(pattern, re.IGNORECASE if os.name == 'nt' else 0) 

for fpath in (os.path.join(dirpath, fn) 
       for fn in os.listdir(dirpath) if fnpat.match(fn)): 
    os.remove(fpath) 
相關問題