Home>Article>Backend Development> How to write variables into txt format line by line in Python
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 thestring:
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
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!