要以UTF-8格式打开文件,可以使用Python的内置open()函数,并指定文件的编码方式为'utf-8'。下面是一个打开并读取文件的例子:
- with open('file.txt', 'r', encoding='utf-8') as file:
- content = file.read()
- print(content)
- with open('file.txt', 'w', encoding='utf-8') as file:
- file.write('Hello, World!')