通过OS shell使用Python删除文件

18

我正在尝试使用通配符删除E盘中的所有文件。

E:\test\*.txt

我宁愿询问而不是测试os.walk。在Windows中。

4个回答

58
你可以使用glob模块来实现这个功能。
import glob
import os
for fl in glob.glob("E:\\test\\*.txt"):
    #Do what you want with the file
    os.remove(fl)

我刚刚在我的电脑上运行了它,它正常工作。你确定你有权限删除那些文件吗?如果你在命令提示符下执行以下操作会发生什么:E:<br />cd test<br />del [filename]? - cwallenpoole
显然,将"[filename]"替换为文件名。 - cwallenpoole
操作系统=Windows,权限:是“E:<br />cd test <br />del [文件名]”在Windows上可以执行吗? - Merlin
1
使用glob模块的原因是什么,为什么它比被接受的答案更受欢迎?(根据答案的投票) 它相对于其他答案有哪些优势? - Aaron
1
@AaronAlphonsus,它允许您在接受的答案中使用*而不是if file.endswith(".txt"): - Or Duan

22

另一种方法的略微冗长描述

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
我宁愿写成:map(os.remove, [os.path.join("E:\test",f)) for f in os.listdir("E:\test") if f.endswith(".txt")]) - DevLounge
优美的解决方案,运行非常出色且跨平台。 - Ash
@AnthonyPerot 为什么使用map比答案中提到的列表推导更好呢? - GaneshTata

0

如果你想用更少的代码行来完成这个任务,你也可以使用popen。

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

6
最好使用Python库,因为这可以使你的代码跨平台、更加健壮,并提供丰富的异常。如果简洁很重要,你可以使用Python本地库在一行中完成相同的操作:#import glob,os ; [os.remove(x) for x in glob.glob("E:\test\*.txt")] - Alastair McCormack

0
如果您想删除具有多个扩展名的文件,则可以像下面这样在元组中定义这些扩展名。
import 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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接