In the python file operation, there is no way to the file specific line or a location of the content of the local modification, if you need to modify a line of the file, you can first read all the contents of the file,
Then the content is judged, whether it is the content that needs to be modified, if it is to replace the content, and will modify the replaced content and the unmodified content is written to the new file.
# 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)
Note:
Contents of the old file:
Hello,worldyanyan is good Girlgood day are good day
What's in the new file after the code executes:
Hello,worldyanyan is good Girlhello,yanyan
Note that the file handle of the old file and the file handle of the new file have a problem with the permissions, if the permissions are wrong, such as the new file does not have write permission, or the old file does not have Read permission, then the whole code will be invalidated
Python modifies the contents of a file