Write __python for Python files

Source: Internet
Author: User

The Wirte () method writes the string to a file, and the Writelines () method writes the contents stored in the list to the file.

F=file ("Hello.txt", "w+")

li=["Hello world\n", "Hello china\n"]

F.writelines (LI)

F.close ()


Contents of the file:

Hello World

Hello

Both the Write () and Writelines () methods erase the contents of the file before writing, and then write back to the new content, equivalent to the "overwrite" method. If you need to keep the contents of the original file, you just need to append new content, you can use the "A +" mode

Open the file.


F=file ("Hello.txt", "A +")

New_context= "Goodbye"

F.write (new_content)

F.close ()

The contents of this hello.txt are as follows:

Hello World

Hello

Goodbye


Practice:

>>> f=file ("Hello.txt", "w+")
>>> li=["Hello world\n", "Hello china\n"]
>>> F.writelines (LI)
>>> F.close ()
>>>
>>> f=file ("Hello.txt", "A +")
>>> new_context= "Goodbye"

>>> F.write (new_content)
>>> F.write (new_content)
>>> F.close ()

Results:

Hello World
Hello
Goodbyegoodbye




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.