我有以下输出,我想将其写入文件:
l = ["Bücher", "Hefte, "Mappen"]
我这样做是这样的:
f = codecs.open("testfile.txt", "a", stdout_encoding)
f.write(l)
f.close()
在我的文本文件中,我想看到:["Bücher", "Hefte, "Mappen"] 而不是 B\xc3\xbccher
有没有办法不遍历列表并解码每个项目?想给 write() 函数任何参数吗?
非常感谢
请您参考如下方法:
首先,确保使用 unicode 字符串:将“u”前缀添加到字符串中:
l = [u"Bücher", u"Hefte", u"Mappen"]
然后您可以写入或追加到文件:
我建议您使用 io与 Python 2/3 兼容的模块。
with io.open("testfile.txt", mode="a", encoding="UTF8") as fd:
for line in l:
fd.write(line + "\n")
要一次性阅读您的文本文件:
with io.open("testfile.txt", mode="r", encoding="UTF8") as fd:
content = fd.read()
结果 content 是一个 Unicode 字符串。
如果你使用 UTF8 编码解码这个字符串,你会得到这样的 bytes 字符串:
b"B\xc3\xbccher"
编辑使用writelines。
writelines() 方法将一系列字符串写入文件。序列可以是任何可生成字符串的可迭代对象,通常是字符串列表。没有返回值。
# add new lines
lines = [line + "\n" for line in l]
with io.open("testfile.txt", mode="a", encoding="UTF8") as fd:
fd.writelines(lines)
