W3docs

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".

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:

Read a file in Unicode (UTF-8) encoding in Python using open() function

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

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

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:

Write a file in Unicode (UTF-8) encoding in Python using open() function

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.