There are multiple string variables to write to the file

Asked 2 years ago, Updated 2 years ago, 47 views

There are multiple string variables to write to the file.

x="Hello World"
y="google"
z = "deep learning is very popular now"

There are three variables:I'd like to write this x·y·z to a text file.

f=open('text.txt', 'w')
f.writelines(x)
f.writelines(y)
f.writelines(z)
f.close()

Should I write that?Or

f=open('text.txt', 'w')
f.writelines(x)
f.close()

f = open ('text.txt', 'w')
f.writelines(y)
f.close()

f = open ('text.txt', 'w')
f.writelines(z)
f.close()

Should I write that?I don't feel any of them are neat, so if there is a better way to write it, please do so.
By the way, the text file contains

Hello World
google
deep learning is very popular now

I would like to write one column at a time as shown in .

python

2022-09-30 21:31

3 Answers

How about doing the following?

s="\n".join([x,y,z])#'\n' represents a newline code
# Put it in the x,y,z list and combine it with a new line code.

f=open("text.txt", "w")#text.txt in write mode
US>f.write(s)# Write to file 
f.close()#Close the file


2022-09-30 21:31

I use the pathlib module because I want to write in one line.
I use with open internally, so the file is automatically closed().
If you add the import statement, it says two lines, but don't worry.I think it's good that you don't have to indent.

import pathlib
pathlib.Path("test.txt").write_text('{}\n{}\n{}\n'.format(x,y,z))

The following writing method is shorter, so I often use it, but please avoid connecting many strings because it reduces the speed and memory efficiency of string connections.If it's just a question example string, there's no problem.

pathlib.Path("test.txt").write_text(x+"\n"+y+"\n"+z+"\n")

The following writing methods may be best because they have less speed, efficiency, and number of characters.

pathlib.Path("test.txt").write_text("\n".join([x,y,z])+"\n")

The expression "\n".join" may be uncomfortable, but this expression is standard in python.
Please refer to the official wiki information regarding string concatenation below.
https://wiki.python.org/moin/PythonSpeed/PerformanceTips#String_Concatenation

In addition, I think the idea of opening three times is probably a way of not being able to speed up.Basically, it is better to assemble strings in memory and interact with files as little as possible (one time).


2022-09-30 21:31

It depends on the person and the situation, but
First of all, how about this code?

with open('text.txt', 'w') asf:
  f.write(f'{x}\n{y}\n{z}\n')

Python 3.6 or higher is required.


2022-09-30 21:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.