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

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 can call the file handle’s write method with a Unicode encoded string.

For instance, we write:

foo = u'Δ, Й, ק, ‎ م, ๗, あ, 叶, 葉, and 말.'
f = open('test', 'w')
f.write(foo)
f.close()

f = open('test', 'r')
print(f.read())

We define the string foo with a Unicode string.

Then we open the test file with open with write permission.

Next, we call f.write with foo and then close the file with close.

Then to read the file, we call open again with the file path and 'r' to get read permission.

And then we call f.read.

Therefore print should print 'Δ, Й, ק, ‎ م, ๗, あ, 叶, 葉, and 말.'.

Conclusion

To write Unicode text to a text file with Python, we can call the file handle’s write method with a Unicode encoded string.