In python3, the file input and output features, and how to overwrite the file content and the next input,

Source: Internet
Author: User

In python3, the file input and output features, and how to overwrite the file content and the next input,

Today I met a very interesting python feature. Originally, I wanted to open a file and input some content at the end of the file. The Code is as follows:

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

The result shows that no matter what I write, the content is always written from the beginning of the file and overwrites the original content. I checked the official documentation and did not know how to do it.

But by accident, I found the method of writing to the end. The Code is as follows:

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

Yes, just adding a row of f. read (), your write function will automatically be written to the end. After reviewing the official documentation, it seems that this is not mentioned.

 
 
read( size)

Read and return at most 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.

 

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.