简体   繁体   English

Python:遍历目录和子目录

[英]Python: Iterate through directory and subdirectory

I want to delete the whole content of 3.000 files using python and keep only some specific lines. 我想使用python删除3.000个文件的全部内容,并仅保留一些特定的行。

File.txt File.txt

    Motion
    FileName "d:/monster"
    Dur 0.6321
    Acc 0.1121
    SOME LINE
    ASD
    SDAF
    DS
    V
    SADF
    SDV
    SDAFAV

This code Works perfect for a single file 此代码非常适合单个文件

with open(x, "r+") as f:
    new_f = f.readlines()
    f.seek(0)

    for line in new_f:
        if re.match(r"^(Dur|Acc)", line):
            f.write(line)

    f.truncate()

I tried this way, to iterate through all files with extension .txt 我尝试过这种方式,以遍历​​所有扩展名为.txt的文件

files = glob.glob('dirtest')
for x in files:

    with open(x, "r+") as f:
        new_f = f.readlines()
        f.seek(0)

        for line in new_f:
            if re.match(r"^(Dur|Acc)", line):
                f.write(line)

        f.truncate()

But nothing happens. 但是什么也没发生。 How should the final script look? 最终脚本应如何显示? To iterate through all 3.000 files 遍历所有3.000个文件

You can try to use listdir 您可以尝试使用listdir

import os
for file in os.listdir("filesPath"):
     if file.endswith(".txt"):
         with open(x, "r+") as f:
             new_f = f.readlines()
             f.seek(0)
             for line in new_f:
                 if re.match(r"^(Dur|Acc)", line):
                 f.write(line)

             f.truncate()

Hope it helps 希望能帮助到你

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

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