0

I try to play with number while practice python and i try to save it as a text or word document, but when saved, the file doesn't have a format, and i think python default saved it as a text file (.txt) but i m wrong its saved like a unknown format file

this is my code

    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 )

and when i try to open it with notepad it writen in one line, like this:

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

what must i add so it save output as a list, like this:

Number 1:20000
Number 2:30000
Conclusion : Different

Thanks

user3044923
  • 95
  • 1
  • 1
  • 13
  • Watch out, `"%s" % filename` is an anti-pattern, especially since `filename` is already a string. Just do `self.save( filename )` instead. – SethMMorton Jan 03 '14 at 07:09

1 Answers1

2

add \n at the end of the line, for example, change:

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

to:

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

etc.

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • wow it works thank you.. but if you mind i have 1 question again, how can i save file in text (.txt) or word ( .doc), i read in other post that i can add {.encode} but did it requires me to install a codec or add on? – user3044923 Jan 03 '14 at 08:45
  • @user3044923 if you want to save the file with `.txt` extension it's done exactly like you do it. Saving to `.doc` extension is a different story since it's not just a different encoding, it's a different format which requires some kind of processing. Check out the following: http://stackoverflow.com/a/188620/1057429 – Nir Alfasi Jan 03 '14 at 23:48