Unicode (UTF-8) reading and writing to files in Python

To read a file in Unicode (UTF-8) encoding in Python, you can use the built-in open() function, specifying the encoding as "utf-8". Here's an example:

with open("file.txt", "r", encoding="utf-8") as f:
    text = f.read()
    print(text)

Watch a course Python - The Practical Guide

To write a file in Unicode (UTF-8) encoding in Python, you can use the built-in open() function with the 'w' mode and specifying the encoding as "utf-8". Here's an example:

with open("file.txt", "w", encoding="utf-8") as f:
    f.write("Hello, world!")

Please note that in the above example the file will be created if not exist and if the file already exist it will truncate the content before writing.