Python file content Modification replace operation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.