Python:遍历目录和子目录

标签 python

我想使用 python 删除 3.000 个文件的全部内容并只保留一些特定行。

文件.txt

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

此代码非常适合单个文件

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

我尝试了这种方式,迭代所有扩展名为 .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()

但是什么也没发生。 最终的脚本应该是什么样子?迭代所有 3.000 个文件

最佳答案

您可以尝试使用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()

希望对你有帮助

关于Python:遍历目录和子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54544195/

相关文章:

Python:ctypes 和垃圾收集

python - 跟踪python解释器的执行路径

python - Django 多表继承与单独的(相同的)表没有指针

python - 通过python脚本部署到artifactory

python - 将 xcom 值传递给 Airflow 中的 JiraOperator

python - 使用正则表达式解析特殊符号 '( )'

python - 开机后自动运行 python 脚本?

python - 仅在 setup.py 中可能时编译可选的 cython 扩展

python - 如何按值从集合中删除对象

python - 如何计算段落中的单词数并排除一些单词(从文件中)?