【问题标题】:Unable to delete files of certain extension无法删除某些扩展名的文件
【发布时间】:2017-05-05 05:53:32
【问题描述】:

我正在尝试删除文件夹中的一些档案。

这是我为此写的:

import sys
import os
from os import listdir
from os.path import join

dir_path = os.path.dirname(os.path.realpath(__file__))

for file in dir_path:
    if (file.endswith(".gz")) or (file.endswith(".bz2")):
        os.remove(join((dir_path), file))
        print("Removed file.")

print("Done.")

当我运行模块时,它只会打印“完成”。但不删除任何文件,即使在与模块相同的目录中有具有该扩展名的文件。

不知道我做错了什么,帮忙?

【问题讨论】:

    标签: python file python-3.x operating-system delete-file


    【解决方案1】:

    这似乎奏效了:

    import sys
    import os
    from os import listdir
    from os.path import join
    
    dirdir = "/Users/kosay.jabre/Desktop/Programming/Password List"
    dir_path = os.listdir(dirdir)
    
    for file in dir_path:
        if (file.endswith(".gz")) or (file.endswith(".bz2")):
            os.remove(file)
    
    print("Done.")
    

    【讨论】:

    • dirdir 应该是 dir_path 和 dir_path 应该是 files。正确命名变量以使其更有意义。
    【解决方案2】:

    您好像在 for 循环中错过了 os.listdir(dir_path)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-20
      • 2020-02-27
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多