When we read the contents of the file, if we want to modify the contents of a line or a location in the file, there is no way to implement in Python, if you want to implement such an operation can only first read all the contents of the file, and then make a matching modification to write to the new file.
The instance code is as follows:
# open old Files f = open (' File_text.txt ', ' R ', encoding= ' Utf-8 ') # Opens new File F_new = open (' File_text_bak.txt ', ' W ', encoding= ' Utf-8 ') # Loop through the old file for line in F: # To determine if "Good Day is Good day" on line: Line = Line.replace (' Good Day was good day ', ' he Llo,yanyan ') # If it does not match it will normally read the contents of the file and output it to a new file F_new.write (line)
F.close ()
F_new.close ()
Note:
1. Contents of old files
Hello,world
Yanyan is Good girl
Good Day was good day
2. What the new file is after the code executes
Hello,world
Yanyan is Good girl
Hello,yanyan
3. Need to be aware of the issue of permissions, for the old file must have Read permission, for the new file must have write permission
Python file content Modification replace operation