【发布时间】:2019-10-15 02:31:21
【问题描述】:
我的文件夹中几乎没有包含印地语文本的文本文件。但是那些文本文件在UTF-16 LE 编码中。我想将编码更改为 UTF-8 而不更改其中的文本。我该怎么做?
我编写了两个 python 文件,但它们都没有正常工作。当我运行它们中的任何一个以及更改编码时,它们会清除文件内容。这些是我的 Python 文件中的代码:
文件 1:
import os
for root, dirs, files in os.walk("."):
for filename in files:
#print(filename[-4:])
if(filename[-3:] == "txt"):
f= open(filename,"w+")
x = f.read()
print(x)
f.close()
f1= open(filename, "w+", encoding="utf-8")
f1.write(x)
f1.close()
文件 2:
import codecs
BLOCKSIZE = 1048576
with codecs.open("ee.txt", "r", "utf-16-le") as sourceFile:
with codecs.open("ee.txt", "w", "utf-8") as targetFile:
while True:
contents = sourceFile.read(BLOCKSIZE)
print(contents)
if not contents:
break
targetFile.write(contents)
【问题讨论】:
标签: python unicode utf-8 utf-16 file-encodings