在python中将unicode utf-8数据写入文件时出现问题

0 python unicode utf-8

我在Python程序中将unicode写入文件时遇到了一些问题.

以下是"保存"文件的代码:

def file_save(self):
    # save changes to existing file
    if self.filename and isfile(self.filename):

        self.watcher.removePath(self.filename)
        s = codecs.open(self.filename,'w','utf-8')
        s.write(unicode(self.ui.editor_window.toPlainText()))
        s.close()
        self.ui.button_save.setEnabled(False)
        self.watcher.addPath(self.filename)
    # save a new file
    else:
        fd = QtGui.QFileDialog(self)
        newfile = fd.getSaveFileName()
        if newfile:
            s = codecs.open(newfile,'w','utf-8')
            s.write(unicode(self.ui.editor_window.toPlainText()))
            s.close()
            self.ui.button_save.setEnabled(False)
Run Code Online (Sandbox Code Playgroud)

一旦调用该方法,我收到此错误消息:

line 113, in file_save
s.write(unicode(self.ui.editor_window.toPlainText()))
NameError: global name 'unicode' is not defined
Run Code Online (Sandbox Code Playgroud)

我正在运行Python 3.2,似乎无法在任何地方找到问题.

Ign*_*ams 5

Unicode支持在3.x中被"修复".正常的字符串文字存储为Unicode,而普通open()函数获得了一个encoding参数,从而使其codecs.open()过时.

    s = open(self.filename, 'w', encoding='utf-8')
    s.write(self.ui.editor_window.toPlainText())
Run Code Online (Sandbox Code Playgroud)