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

前端 未结 3 846
[愿得一人]
[愿得一人] 2020-11-30 08:10

I am trying to replace text in a text file by reading each line, testing it, then writing if it needs to be updated. I DO NOT want to save as a new file, as my script alrea

3条回答
  •  半阙折子戏
    2020-11-30 08:28

    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 '
                                                            
提交回复
热议问题