I'm Python New B. How do I write str type in a file?

Asked 2 years ago, Updated 2 years ago, 110 views

apples = 'Hello World!'
text_file = open("Output.txt", "w")

text_file.write("message :", mystr)

text_file.close()

In the print function, print("message:", mystr) was separated by commas, but it didn't work in write.

How can I write a string type to a file?

string file-io python write text

2022-09-21 14:33

1 Answers

It is true that both print and write are output, but the writing method is slightly different.

print (*objects, sep='', end='\n', file=sys.stdout, flush=False) can receive multiple strings (or other objects) from *objects Because write(s) receives only one string type factor.

So we can't write because the comma-separated method is "multiple factors." So when you write, you have to combine the two strings into one. I'll write down a few representative methods

text_file.write("message: %s" %mystr)
text_file.write("Purchase Amount: {0}".format(TotalAmount))
text_file.write("Purchase Amount: {}".format(TotalAmount))
print("Purchase Amount: {}".format(TotalAmount), file=text_file)


2022-09-21 14:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.