Categories
Python Answers

How to write Unicode text to a text file with Python?

Spread the love

Sometimes, we want to write Unicode text to a text file with Python.

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

How to write Unicode text to a text file with Python?

To write Unicode text to a text file with Python, we call the file’s open method with the encoding argument.

For instance, we write

s = "南"
f = open("t1.txt", "w", encoding="utf-8")
f.write(s)
f.close()

to open the t1.txt file with write permission with open.

We call it with encoding set to 'utf-8' to open it as a Unicode text file.

Then we call f.write with string s to write the content to t1.txt.

And then we call close to close the file.

Conclusion

To write Unicode text to a text file with Python, we call the file’s open method with the encoding argument.

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 *