0

Hi I'm trying to write a python script that will...

find and replace certain values in a file. The problem being there are multiple files called the same name and not all of them will have the values.

It would also be good to take backup of the file before changing the values.

So far I have managed to get as far as searching for the file with the name test1.txt. the out put shows multiple locations of where it has found test1.txt next I need it to search for the values such as "Scott" and replace it with " John" and take a backup before changing it if possible.

Not all the test1.txt found will have the name "Scott" so I don't really want to take a backup of them all.

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/')
  • 2
    Does this answer your question? [Search and replace a line in a file in Python](https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) – Alex Jan 24 '20 at 11:45
  • thats close suggestion but the problem I'm having is the location of the file maybe in different location and only 1 file out of 3 found would need updating. – Scott Marriott Jan 24 '20 at 11:53
  • This is not actually an question, imho. The link should provide enough pointers to help you. It depends on the size of your files, if they are small-ish, you are probably fine with .read(), so you dont need to worry about looping through lines. You want to take a look at 'shutil' module for backups. I would probably open for each file new one (with different name) where I would prepare replaced text and only flush it (write) if you changed anything. In that case I would I would use shutil to move(rename) old file as a backup, new file as an original file. – Dolfa Jan 24 '20 at 12:13

0 Answers0