0

i have this two methods one to read a file

def openfile(self):
    dialog= QFileDialog()
    dialog.setFileMode(QFileDialog.AnyFile)
    dialog.setFilter(QDir.Files)

    if dialog.exec_():
        file_name= dialog.selectedFiles()
        path = file_name[0]

        if file_name[0].endswith('.py'):
            with open(file_name[0],'r') as f:
                data= f.read()
                self.textEdit.setText(data)
                f.close()
        else:
            pass

and the second method is save the file

def save(self):
    print("saved")
    text = self.textEdit.text()
    file = open(filename,'w')
    file.write(text)
    file.close()

i want to use the variable 'filename' in the second method without losing it's value

Yazid Med
  • 57
  • 6
  • 1
    use `self.filename` instead of `filename`. On the other hand if you use `with open(...) as f:` then it is not necessary to use `f.close()`, that's the advantage of using it over `open(...)` without `with`. – eyllanesc Nov 17 '21 at 19:23

0 Answers0