File input and output features under Python3 and how to overwrite file contents and next input

Source: Internet
Author: User

A very interesting Python feature was encountered today. Originally I want to open a file, at the end of the file to enter some content, the code is as follows:

f = open ('test.txt'r+') f.write (content) F.close ()

It turns out that no matter what I write, content is always written from the beginning of the file and overwrites the original content. I checked the official documents and didn't know what to do.

But by chance I found the method that was written at the end of the code as follows:

f = open ('test.txt'r+') f.read () f.write (content ) F.close ()

Yes, just add a line of F.read () and your write function will automatically be written to the end. Went over the official document, seemingly without mentioning it.

read ( size)

Read and return at the very size characters from the stream as a single str . If size is negative or None , reads until EOF.

write ( s)

Write The string s to the stream and return the number of characters written.

File input and output features under Python3 and how to overwrite file contents and next input

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.