Python file Write instance analysis _python

Source: Internet
Author: User
Tags in python

This example describes the use of Python file writes. Share to everyone for your reference. The specific analysis is as follows:

The Wirte () method in Python writes a string to a file, and the Writelines () method writes the contents stored in the list to a 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 file, you just need to append new content, 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 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

I hope this article will help you with your 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.