How Python writes variables to the TXT format in a row

Source: Internet
Author: User
This time, we bring you python. How to write variables in the TXT format, python to write variables in the TXT format of the note, the following is the actual case, take a look.

Let's look at a simple example: write a variable into the txt text

f = open (' E:/test.txt ', ' W ') f.write (' Hello world! ') OUT[3]: F.close ()

Results

So how do you write a variable on a row?

In the ' W ' write mode, the next time we write a variable, it overwrites the contents of the original TXT file, which is definitely not what we want. TXT has an append mode ' a ' that enables multiple writes:

f = open (' E:/test.txt ', ' a ') f.write (' The second writing ... ') out[6]: F.close ()

Results

If you want to write by line, we only need to add the line break ' \ n ' at the beginning or end of the string:

f = open (' E:/test.txt ', ' a ') f.write (' \nthe third writing ... ') out[9]: F.close ()

Results

If you want to write multiple variables to a row at the same time, you can use the Writelines () function:

f = open (' E:/test.txt ', ' a ') f.writelines ([' \nthe fourth writing ... ', ', ', ' good ']) F.close ()

Results

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

How does python achieve the Markov distance

How Python calls MySQL to update data

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.