Menu Close

How to print string to a text file with Python?

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.

Posted in Python, Python Answers