python文件输出中文_Python输出中文到文件时的字符编码问题

今天在使用Python的GUI平台wxPython时,写了一个只有打开、编辑、保存功能的简易笔记本,代码如下:

1 #coding:utf-8

2 importwx3

4 defload(event):5 f =open(FileName.GetValue())6 Contents.SetValue(f.read().decode('utf-8'))7 f.close()8

9 defsave(event):10 f = open(FileName.GetValue(), 'w')11 f.write(Contents.GetValue())12 f.close()13

14 app =wx.App()15 win = wx.Frame(None, title = "Simple Editor", size = (410, 335))16 bkg =wx.Panel(win)17

18 LoadButton = wx.Button(bkg, label = "Open")19 LoadButton.Bind(wx.EVT_BUTTON, load)20 SaveButton = wx.Button(bkg, label = "Save")21 SaveButton.Bind(wx.EVT_BUTTON, save)22 FileName =wx.TextCtrl(bkg)23 Contents = wx.TextCtrl(bkg, style = wx.TE_MULTILINE |wx.HSCROLL)24

25 hbox =wx.BoxSizer()26 hbox.Add(FileName, proportion = 1, flag =wx.EXPAND)27 hbox.Add(LoadButton, proportion = 0, flag = wx.LEFT, border = 5)28 hbox.Add(SaveButton, proportion = 0, flag = wx.LEFT, border = 5)29

30 vbox =wx.BoxSizer(wx.VERTICAL)31 vbox.Add(hbox, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)32 vbox.Add(Contents, proportion = 1, flag = wx.EXPAND | wx.LEFT | wx.BOTTOM |wx.RIGHT,33 border = 5)34

35 bkg.SetSizer(vbox)

36 win.Show()37

38 app.MainLoop()

但是在使用过程中输入中文保存时,控制台报错:

Traceback (most recent call last):

File "D:\coding_file\python_file\TestPython\src\Test\test1.py", line 11, in save

f.write(Contents.GetValue())

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

这里需要特别注意第六行代码中的 f.read().decode('utf-8'),因为字符串在Python内部的表示是Unicode编码,所以使用decode('utf-8'),表示用utf-8编码对文件进行解码,从而将文件中的字符串转换为Unicode编码。

由于Python默认使用Unicode编码,所以需要手动设置编码如utf-8,改动如下:

1 importwx, sys2 reload(sys)3 sys.setdefaultencoding('utf-8')

这样就可以输入中文并保存了,其中要特别注意 reload(sys)这一行代码

reload()函数将以前导入过的模块再加载一次。重新加载(reload)包括最初导入模块时应用的分析过程和初始化过程。这样就允许在不退出解释器的情况下重新加载已更改的Python模块,从而改变字符集编码为UTF-8,问题解决。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值