Categories
Python Answers

How to print string to a text file with Python?

Spread the love

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

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

How to print string to a text file with Python?

To print string to a text file with Python, we can use the open and write methods.

For instance, we write:

with open("output.txt", "w") as text_file:
    text_file.write("foo")

We open the file we want to write to with a with statement and the open function.

We pass in the path of the text file and the permission as arguments of open.

In the block, we call text_file.write to write the string into the text file.

text_file is the file handle for the text file.

And the file will be closed automatically once the write operation is done since we used the with statement.

Conclusion

To print string to a text file with Python, we can use the open and write methods.

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 *