如果名称满足条件,则删除特定扩展名的文件

rod*_*ocf 1 python file python-3.x

我不确定这是否简单,但我有一个文件夹,里面有很多 csv 和 txt 文件。我需要删除名称末尾没有 0 的所有 CSV 文件。我有一个简单的方法来做到这一点?

以防万一该文件夹与我的脚本所在的文件夹相同,因此无需输入文件路径。我正在运行 python 3.3.3。任何想法都非常感谢!!

谢谢!!

Ada*_*ith 5

与 Padraic 的出色回应一样:

import os, glob
files = [file for file in glob.glob("path/to/files/*.csv") if not file.endswith("0.csv")]
for file in files:
    os.remove(file)
Run Code Online (Sandbox Code Playgroud)

我认为首先构建列表并迭代删除看起来更简洁。天啊。我喜欢这样做,因为这样我就可以写出类似的东西:

with open("path/to/files/file_removal.log","w") as f:
    for file in files:
        try:
            os.remove(file)
        except Exception as e:
            f.write("! The file {} could not be removed:\n".format(file)+
                    "-->{}\n".format(e))
        else:
            f.write("The file {} was removed successfully\n".format(file))
Run Code Online (Sandbox Code Playgroud)

  • 这里也一样,应该是 `... if not file.endswith("0.csv")]`。此外,`file` 是一种内置类型,应避免作为变量名。 (2认同)