Python file write instance analysis

Source: Internet
Author: User
This article mainly introduces the usage of writing python files. The example analyzes the usage skills of writing Python files, which is of great practical value, for more information about how to write python files, see the example in this article. Share it with you for your reference. The specific analysis is as follows:

In Python, the wirte () method writes a string to a file. the writelines () method can write the content stored in the list to a file.

f=file("hello.txt","w+")li=["hello world\n","hello china\n"]f.writelines(li)f.close()

File content:

hello worldhello china

The write () and writelines () methods clear the original content of the file before writing, and then re-write the new content, which is equivalent to the "overwrite" method. To retain the original content of the file, you can use the "a +" mode to open the file.

f=file("hello.txt","a+")new_context="goodbye"f.write(new_content)f.close()

The content in hello.txt is as follows:

hello worldhello chinagoodbye

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()

Result:

hello worldhello chinagoodbyegoodbye

I hope this article will help you with Python programming.

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.