Simple file Operations Python modifies a file to specify a line method

Source: Internet
Author: User
Example one:
Copy the Code code as follows:


#!/usr/bin/python
Import Sys
Import re
If __name__== "__main__":
F=file ("Hi.txt", "w+")
li=["hello\n", "hi\n"]
F.writelines (LI)
F.close ()


"w+" mode: Creates a file write if there is no hi.txt and, if present, empties the Hi.txt content and writes from the new.

Example two: Modifying a file to specify a line

The method is more stupid, read the contents of the file into a list in a row, modify the specified line to assign values to the elements in the list, and after the modification, use Writelines to write the list to a new file.


Copy the Code code as follows:


#!/usr/bin/python

Import Sys,os

F=open (' Hi.txt ', ' r+ ')
Flist=f.readlines ()
flist[4]= ' hi\n '
F=open (' Hi.txt ', ' w+ ')
F.writelines (Flist)


Change the contents of Hi.txt line fifth to hi
  • Related Article

    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.