【问题标题】:Delete files with python through OS shell通过 OS shell 使用 python 删除文件
【发布时间】:2011-07-28 19:09:08
【问题描述】:

我想删除 E: 中的所有文件。 带通配符。

E:\test\*.txt

我会问而不是测试 os.walk。 在窗户里。

【问题讨论】:

    标签: python file


    【解决方案1】:

    您可以使用glob 模块:

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

    【讨论】:

    • 我刚刚在我的机器上运行了它,它运行良好。您确定您有权删除这些文件吗?如果您在命令 promt 上执行以下操作会发生什么:E:
      cd test
      del [filename]?
    • 显然将“[filename]”替换为文件名。
    • OS= windows,权限:是 "E:
      cd test
      del [filename]" 在 windows 上??
    • 是否有理由使用 glob 模块是首选的方法而不是接受的答案? (按答案投票)与其他答案相比,它有什么优势?
    • @AaronAlphonsus 它让您在接受的答案中使用* 而不是if file.endswith(".txt"):
    【解决方案2】:

    另一种方法的稍微冗长的写法

    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(os.remove, [os.path.join("E:\\test",f)) for f in os.listdir("E:\\测试") if f.endswith(".txt")])
    • 漂亮的解决方案,令人惊叹,而且是跨平台的。
    • @AnthonyPerot 为什么使用map 比答案中提到的列表理解更好?
    【解决方案3】:

    如果你想用更少的行来做,你也可以使用 popen

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

    【讨论】:

    • 最好使用 Python 库,因为它使您的代码跨平台,不那么脆弱并提供丰富的异常。如果简洁很重要,您可以在一行中使用 Python 原生库实现相同的目的:#import glob,os ; [os.remove(x) for x in glob.glob("E:\test\*.txt")]
    【解决方案4】:

    如果要删除具有多个扩展名的文件,请在元组中定义这些扩展名,如下所示

    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多