首页 > 解决方案 > Python 搜索文件并查找和替换值

问题描述

嗨,我正在尝试编写一个 python 脚本,它将...

查找和替换文件中的某些值。问题是有多个同名文件,并非所有文件都具有这些值。

在更改值之前备份文件也很好。

到目前为止,我已经设法搜索到名为 test1.txt 的文件。输出显示了它找到 test1.txt 的多个位置接下来我需要它来搜索诸如“Scott”之类的值并将其替换为“John”,并在可能的情况下进行更改之前进行备份。

并非所有找到的 test1.txt 都具有名称“Scott”,所以我真的不想对它们进行备份。

import os
filename[]
def find_files(filename, search_path):
    result = []
    for root, dirs, files in os.walk(search_path):
        if filename in files:
            result.append(os.path.join(root, filename))
    return result

print(find_files("test1.txt", '/home/')

标签: pythonreplacefind

解决方案


推荐阅读