2011-04-03 62 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