To write Unicode text to a text file with Python, you need to ensure that you open the file in the appropriate encoding. Here’s an example using the UTF-8 encoding:
text = "Unicode text: äöüß"
with open("output.txt", "w", encoding="utf-8") as file:
file.write(text)
In this example:
- The
text
variable contains the Unicode text you want to write to the file. - The
open()
function is used to open the file named “output.txt” in write mode (“w”). - The
encoding="utf-8"
parameter specifies the UTF-8 encoding, which supports Unicode characters from various languages. - The file is opened using a
with
statement, which ensures that the file is properly closed after writing.
When you use the write()
method of the file object, Python will automatically encode the Unicode text as UTF-8 and write it to the file.
After running this code, the “output.txt” file will contain the Unicode text: “Unicode text: äöüß”. You can replace the file name with the desired path or filename to write to a different location.
Make sure to choose the appropriate encoding based on your requirements. UTF-8 is a widely used encoding that supports a wide range of Unicode characters, but there are other encodings available as well.
By specifying the correct encoding when opening the file, you can write Unicode text to a text file using Python.
+ There are no comments
Add yours