Search and replace a line in a file in Python

前端 未结 13 1658
傲寒
傲寒 2020-11-21 07:40

I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory

13条回答
  •  北海茫月
    2020-11-21 08:11

    Based on the answer by Thomas Watnedal. However, this does not answer the line-to-line part of the original question exactly. The function can still replace on a line-to-line basis

    This implementation replaces the file contents without using temporary files, as a consequence file permissions remain unchanged.

    Also re.sub instead of replace, allows regex replacement instead of plain text replacement only.

    Reading the file as a single string instead of line by line allows for multiline match and replacement.

    import re
    
    def replace(file, pattern, subst):
        # Read contents from file as a single string
        file_handle = open(file, 'r')
        file_string = file_handle.read()
        file_handle.close()
    
        # Use RE package to allow for replacement (also allowing for (multiline) REGEX)
        file_string = (re.sub(pattern, subst, file_string))
    
        # Write contents to file.
        # Using mode 'w' truncates the file.
        file_handle = open(file, 'w')
        file_handle.write(file_string)
        file_handle.close()
    

提交回复
热议问题