简体   繁体   English

Python:遍历/mydir下的所有目录,删除所有名称中带有“(1)”的文件

[英]Python: traverse all directories under /mydir and remove all files with "(1)" in name

I am trying to remove all files with "(1)" in name under /mydir and sub directories.我正在尝试删除 /mydir 和子目录下名称为“(1)”的所有文件。 I have searched and found a script how to find all files with "*.txt" as below.我已经搜索并找到了一个脚本,如何查找所有带有“*.txt”的文件,如下所示。 How to replace the "if" condition sentense to find all files with "(1)" in name?如何替换“if”条件句以查找名称中带有“(1)”的所有文件?

import os for root, dirs, files in os.walk("/mydir"): for file in files: **if file.endswith(".txt")**: os.remove(os.path.join(root, file))

You can do that like this:你可以这样做:

import os
for root, dirs, files in os.walk("/mydir"):
    for file in files:
        if "(1)" in file:
            os.remove(os.path.join(root, file))

First we import the os module for walk , remove , and join methods.首先,我们为walkremovejoin方法导入os模块。 Then iterate over the tuples yielded by os.walk .然后遍历os.walk产生的元组。 Then iterate over the files returned and check whether the filename contains the string "(1)".然后遍历返回的文件并检查文件名是否包含字符串“(1)”。 If it matches, we concatenate the file name with the directory using os.path.join and then remove the file with os.remove .如果匹配,我们使用os.path.join将文件名与目录连接,然后使用os.remove删除文件。

You can do this very easy with pathlib :您可以使用pathlib轻松完成此操作:

from pathlib import Path
for file in Path("/mydir").glob("*(1)*.*"):
    print(file)
    #file.unlink()

My recommendation is to print all files to delete first (as shown), and only uncomment the file.unlink() line once you are sure that the right files will be deleted.我的建议是首先打印所有要删除的文件(如图所示),并且只有在确定将删除正确的文件后才取消注释file.unlink()行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM