Categories
Python Answers

How to print string to text file with Python?

Spread the love

Sometimes, we want to print string to text file with Python.

In this article, we’ll look at how to print string to text file with Python.

How to print string to text file with Python?

To print string to text file with Python, we can use the write method.

For instance, we write

with open("output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % total)

to call open to open the output.txt with write permission.

Then we call text_file.write to append a line of text into the file.

The file is closed after writing the line since we used with with open.

Conclusion

To print string to text file with Python, we can use the write method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *