import fileinput for line in fileinput.input( " File path to modify ", inplace=1): line=line.replace(" String to modify 1"," String to replace 1") If you need more than one line, you can copy the above line print(line,end="")
After execution, go to the modified file to see the modified file
1. Be sure to add. print(line), Otherwise, the source file will become blank after replacement
2.python3 in print() To add end=“”, Otherwise, there is a blank line after each line of the file after replacement
because print The default is line feed ,end=“” Defines that the newline character is empty .