作者poopoo888888 (阿川)
看板Python
标题[问题] 存成txt档时的编码问题
时间Fri Sep 16 18:23:59 2011
各位大大好 最近小弟在网路上fetch资料时遇上了问题
我抓了一篇中文文章 存在变数content内
接着要把它存成txt档
file = open("test.txt", "wb")
file.write(content)
用记事本去看那个txt档~正确显示
按下另存新档 会得知目前是用utf-8编码 一切顺利
接下来小弟想让一个字存成一行
也
就
是
像
这
样
去
存
小弟的code是这样写
file = open("test.txt", "wb")
for c in content:
file.write(c)
file.write("\n")
结果得到的档案会是乱码
用记事本查看 发现它用ANSI去存 是这边出错了吧?
请问我该如何控制txt档的编码呢?我要指定他用utf-8
劳烦各位大大解惑了 谢谢!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.231.24.220
1F:→ kdjf:len('我') ==> 3 你觉得呢? 09/16 18:37
2F:→ kdjf:要不然来用python3吧 09/16 18:37
3F:→ kdjf:想到了,可以用unicode string 09/16 18:44
4F:→ kdjf:content.decode('utf-8')可以拿到你想要的 09/16 18:45
5F:→ poopoo888888:k大 file.write()是不是都会以ascii去编码啊 09/16 19:32
6F:→ poopoo888888:它在write时显示error耶 说ascii codec无法去编那些 09/16 19:33
7F:→ poopoo888888:unicode string 09/16 19:33
8F:→ poopoo888888:write()的编码器要怎麽换呢? 09/16 19:33
9F:推 aknow:python3 open( , mode='w', encoding='utf-8') 09/16 20:15
10F:→ kdjf:file.write(c.encode('utf-8')) 09/16 20:42
11F:→ poopoo888888:解决了!非常感谢两位大大的帮助! 09/17 08:55