2010-06-03 69 views
0

我正在運行一個腳本,該腳本遍歷目錄結構並在目錄中的每個文件夾中生成新文件。我想在創建後立即刪除一些文件。這是我的想法,但它是錯誤的我想象:刪除Python中的某些文件類型

directory = os.path.dirname(obj) 
m = MeshExporterApplication(directory) 
os.remove(os.path.join(directory,"*.mesh.xml")) 

如何將通配符放入路徑?我想不喜歡/home/me/*.txt,但這正是我正在嘗試的。

感謝, 加雷思

回答

4

可以使用glob模塊:

import glob 
glob.glob("*.mesh.xml") 

獲得匹配的文件列表。然後你逐個刪除它們。

directory = os.path.dirname(obj) 
m = MeshExporterApplication(directory) 

# you can use absolute pathes in the glob 
# to ensure, that you're purging the files in 
# the right directory, e.g. "/tmp/*.mesh.xml" 
for f in glob.glob("*.mesh.xml"): 
    os.remove(f) 
+0

他還需要'os.path.join'。 – 2010-06-03 00:58:50

+0

或glob中的絕對路徑。 – miku 2010-06-03 00:59:16

0

做一個循環的文件列表作爲你循環的東西。

directory = os.path.dirname(obj) 
m = MeshExporterApplication(directory) 
for filename in os.listdir(dir): 
    if not(re.match(".*\.mesh\".xml ,filename) is None): 
     os.remove(directory + "/" + file)  
+0

'glob.glob'旁邊,有'fnmatch'模塊,意思是「文件名匹配」,比're'更適合......匹配文件名。 – tzot 2010-06-28 15:20:51

相關問題