Home>Article>Backend Development> How to write variables into txt format line by line in Python

How to write variables into txt format line by line in Python

php中世界最好的语言
php中世界最好的语言 Original
2018-04-09 10:38:15 4278browse

This time I will bring youPythonHow to writevariablesinto txt format by rows, Python writes variables into txt format by rowsNotesWhat are they? Here are actual cases. Let’s take a look.

Let’s look at a simple example first: writing variables into txt text

f = open('E:/test.txt','w') f.write('hello world!') Out[3]: 12 f.close()

The result is as shown in the figure:

So how to write variables line by line?

In 'w' writing mode, the next time we write a variable, the content of the original txt file will be overwritten, which is definitely not what we want. TXT has an append mode 'a', which can achieve multiple writes:

f = open('E:/test.txt','a') f.write('the second writing...') Out[6]: 21 f.close()

The result is as shown:

##If we want to write by line, we only need to add the newline character '\n' at the beginning or end of the

string:

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

Result As shown in the figure:

If you want to write multiple variables into one line at the same time, you can use writelines()

Function:

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

The result is as shown in the figure:

I believe you have mastered the method after reading the case in this article, and more How exciting, please pay attention to other related articles on php Chinese website!

Recommended reading:

How to implement Mahalanobis distance in Python

##How Python calls mysql to update data

The above is the detailed content of How to write variables into txt format line by line in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn