在列表中写入文件并在python中保存为.txt或.doc

时间:2014-01-03 06:53:29

标签: python

我尝试在练习python时使用数字,我尝试将其保存为文本或word文档,但保存后,文件没有格式,我认为python默认将其保存为文本文件(.txt),但我错了它保存为未知格式文件

这是我的代码

    def Calculator(self):
        input1 = self.ui.lineEdit1.text()
        input2 = self.ui.lineEdit2.text()
        compare = ''
        if input1 == input2:
            compare = 'Yes its Same Number'
        else:
            compare = 'You input different number'
        self.ui.textBrowser.setPlainText(compare)

    def save(self, savein):
        with open(savein, 'w') as f:
            f.write( 'Number 1 :' + str(self.ui.lineEdit1.text()) )
            f.write( 'Number 2 :' + str(self.ui.lineEdit2.text()) )
            f.write( 'Conclusion :' + str(self.ui.textBrowser.toPlainText()) )
            f.close()
    def savefile(self):
        if self.savein:
              self.save( "%s" % self.savein )
        else:
              self.saveAs()

    def saveAs(self):
        tulis = QtGui.QFileDialog(self).getSaveFileName()
        if filename !="":
            _filename = "%s" % filename
            self.save( _filename )

当我尝试用记事本打开它时,它会写成一行,如下所示:

Number 1 :20000Input 2 :3000000Conclusion :You input different number

我必须添加什么以便将输出保存为列表,如下所示:

Number 1:20000
Number 2:30000
Conclusion : Different

由于

1 个答案:

答案 0 :(得分:3)

在该行的末尾添加\n,例如,更改:

f.write( 'Number 1 :' + str(self.ui.lineEdit1.text()) )

为:

f.write( 'Number 1 :' + str(self.ui.lineEdit1.text()) + '\n')