When python modifies a file, the original file is cleared and overwritten in w mode. You can use the Read (r) method to open it, write it to the memory, and then use the write (w) method to open it. When python modifies a file, the original file is cleared/overwritten in w mode. You can use the Read (r) method to open it, write it to the memory, and then use the write (w) method to open it.
Replace taste with tasting.
Yesterday when I was young and frivolous The taste of life was sweet life taste is sweet As rain upon my tongue
# Read the file to the memory with open (". /fileread.txt "," r ", encoding =" UTF-8 ") as f: lines = f. readlines () # open the file with open (". /fileread.txt "," w ", encoding =" UTF-8 ") as f_w: for line in lines: if" taste "in line: # Replace line = line. replace ("taste", "tasting") f_0000write (line)
2. search replacement or single line replacement in full text
# Text content Yesterday when I was young and frivolous The taste of life was sweet taste of life is sweet As rain upon my tonguetastetastetastetaste
# Define a function, with four parameters # x indicates the name of the file to be updated # y indicates the content to be replaced # z indicates the content to be replaced # s default parameter 1 indicates that only the first matching is replaced string # if the parameter is s = 'G', it indicates that def string_switch (x, y, z, s = 1): with open (x, "r", encoding = "UTF-8") as f: # readlines read the file lines = f in the form of a list. readlines () with open (x, "w", encoding = "UTF-8") as f_w: # define a number, it is used to record the position n = 0 # default option in the list when reading the file. it only replaces the string if s = 1: for line in lines: if y in line: line = line. replace (y, z) f_0000write (line) n + = 1breakf_0000write (line) n + = 1 # output the remaining text content for I in range (n, len (lines): f_0000write (lines [I]) # replace elif s = 'G': for line in lines: if y in line: line = line. replace (y, z) f_0000write (line)
Test
1) the default parameter 1 is used to replace the matched first line.
String_switch ("fileread.txt", "taste", "tasting ") # result Yesterday when I was young and frivolous, The taste of The tasting of life was sweet As rain upon my tonguetastetastetastetaste
2) Global replacement
String_switch ("fileread.txt", "taste", "tasting", "g ") # result Yesterday when I was young and frivolous, The taste of The tasting of life was sweet As rain upon my tonguetastingtastingtastingtasting
For more information about file operations in python, see The PHP Chinese website!