how to replace (update) text in a file line by line

First, you want to write the line whether it matches the pattern or not. Otherwise, you’re writing out only the matched lines.

Second, between reading the lines and writing the results, you’ll need to either truncate the file (can f.seek(0) then f.truncate()), or close the original and reopen. Picking the former, I’d end up with something like:

fpath = os.path.join(thisdir, filename)
with open(fpath, 'r+') as f:
    lines = f.readlines()
    f.seek(0)
    f.truncate()
    for line in lines:
        if '<a href="' in line:
            for test in filelist:
                pathmatch = file_match(line, test)
                    if pathmatch is not None: 
                        repstring = filelist[test] + pathmatch
                        line = line.replace(test, repstring)
        f.write(line)

Leave a Comment