2011-04-03 60 views

回答

11

稍微詳細的另一種方法的寫作

import os 
dir = "E:\\test" 
files = os.listdir(dir) 
for file in files: 
    if file.endswith(".txt"): 
     os.remove(os.path.join(dir,file)) 

或者

import os 
[os.remove(os.path.join("E:\\test",f)) for f in os.listdir("E:\\test") if f.endswith(".txt")] 
+1

我寧願在os.listdir(「E:\\ test」)中爲f寫map:os.remove,[os.path.join(「E:\\ test」,f))if f.endswith (「.txt」)]) – 2016-02-02 19:40:27

+0

美麗的解決方案,驚人的炒作和跨平臺。 – Ash 2016-11-27 06:33:56

40

你這樣做的方式是使用glob模塊:

import glob 
import os 
for fl in glob.glob("E:\\test\\*.txt"): 
    #Do what you want with the file 
    os.remove(fl) 
+0

它沒有工作... – Merlin 2011-04-03 21:28:32

+0

我剛剛在我的機器上運行它,它工作正常。你確定你有權刪除這些文件嗎?如果在命令promt上執行以下操作,會發生什麼情況:E:
cd test
del [文件名]? – cwallenpoole 2011-04-03 23:29:02

+0

顯然用文件的名稱替換「[filename]」。 – cwallenpoole 2011-04-03 23:29:21

0

您可以使用POPEN爲這也是如果你想以更少的行數來完成的話

from subprocess import Popen 
proc = Popen("del E:\test\*.txt",shell=False) 
+3

最好使用Python庫,因爲它使您的代碼跨平臺,不那麼脆弱,並提供了豐富的例外。如果簡潔是很重要的,你可以在一行中使用Python本地庫實現同樣的功能:'#import glob,os; [os.remove(x)for glob.glob(「E:\ test \ *。txt」)]' – 2016-02-02 21:15:01