Im Tyring删除E:中的所有文件.用通配符.
E:\test\*.txt
Run Code Online (Sandbox Code Playgroud)
我会问,而不是测试os.walk.在窗户中.
cwa*_*ole 55
你这样做的方法是使用glob模块:
import glob
import os
for fl in glob.glob("E:\\test\\*.txt"):
#Do what you want with the file
os.remove(fl)
Run Code Online (Sandbox Code Playgroud)
bli*_*sse 17
一个略显冗长的另一种方法的写作
import os
dir = "E:\\test"
files = os.listdir(dir)
for file in files:
if file.endswith(".txt"):
os.remove(os.path.join(dir,file))
Run Code Online (Sandbox Code Playgroud)
要么
import os
[os.remove(os.path.join("E:\\test",f)) for f in os.listdir("E:\\test") if f.endswith(".txt")]
Run Code Online (Sandbox Code Playgroud)