我正在尝试使用通配符删除E盘中的所有文件。
E:\test\*.txt
我宁愿询问而不是测试os.walk。在Windows中。
glob
模块来实现这个功能。import glob
import os
for fl in glob.glob("E:\\test\\*.txt"):
#Do what you want with the file
os.remove(fl)
另一种方法的略微冗长描述
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")]
map
比答案中提到的列表推导更好呢? - GaneshTata如果你想用更少的代码行来完成这个任务,你也可以使用popen。
from subprocess import Popen
proc = Popen("del E:\test\*.txt",shell=False)
#import glob,os ; [os.remove(x) for x in glob.glob("E:\test\*.txt")]
- Alastair McCormackimport os
def purge(dir):
files = os.listdir(dir)
ext = ('.txt', '.xml', '.json')
for file in files:
if file.endswith(ext):
print("File -> " + os.path.join(dir,file))
os.remove(os.path.join(dir,file))
*
而不是if file.endswith(".txt"):
。 - Or Duan