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

前端 未结 3 847
[愿得一人]
[愿得一人] 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:34

    1. Open the file for read and copy all of the lines into memory. Close the file.
    2. Apply your transformations on the lines in memory.
    3. Open the file for write and write out all the lines of text in memory.

    with open(filename, "r") as f:
        lines = (line.rstrip() for line in f)
        altered_lines = [some_func(line) if regex.match(line) else line for line in lines]
    with open(filename, "w") as f:
        f.write('\n'.join(altered_lines) + '\n')
    

提交回复
热议问题