📅  最后修改于: 2023-12-03 15:04:10.095000             🧑  作者: Mango
In Python, writing to a text file as UTF-8 encoding is often necessary for handling foreign characters, symbols, and emojis. This guide will show you how to write a text file with UTF-8 encoding in Python.
To write to a text file with UTF-8 encoding, you can follow these steps:
Here's an example:
# open file in write mode with utf-8 encoding
with open("myFile.txt", mode="w", encoding="utf-8") as file:
# write to the file
file.write("Hello, world! 😃")
# close the file
file.close()
In this code snippet, we opened a file called myFile.txt
in write mode with UTF-8 encoding. Then we wrote the string Hello, world! 😃
to the file. Finally, we closed the file.
Here are some additional tips for writing to text files in Python:
mode="a"
).Writing to a text file with UTF-8 encoding is essential when handling foreign characters and symbols. With this guide, you should now be able to write to a text file with UTF-8 encoding in Python.