首页 > 解决方案 > 替换输出长度不同的控制台输出

问题描述

我有一个程序可以搜索给定存储库中的文件以检查它们是否包含字符串...

print("Searching files for string...")
for folder, dirs, files in os.walk(some_path):
    for file in files:
        if file.endswith(".st") or file.endswith(".jsp"):
            fullpath = os.path.join(folder, file)

            # print fullpath
            print(fullpath, end="\r", flush=True)
            time.sleep(0.5)
            # end print fullpath                

            with open(fullpath, 'r') as read_file:
                for (line_number, line) in enumerate(read_file):
                    if search_term in line:
                        results_array.append({
                            "filepath": fullpath,
                            "line": line_number + 1
                        })

我想将完整路径打印到控制台但替换该行,而不是在循环迭代时控制台变得充满输出。使用当前代码,经过几次迭代,输出开始与前几行合并,我假设这是因为每次迭代的路径大小不同。

例如,当前代码的输出:/somepath/example/hello-world.jspfirm.jspidgetsconfig.jsppjspdeals.jsp

我该如何解决这个问题,以便干净地打印和删除每个完整路径?

标签: python-3.xloops

解决方案


推荐阅读