K
K
Kurum2017-02-28 10:24:06
PyQt
Kurum, 2017-02-28 10:24:06

PyQt4 | What is the best way to read a list from a file?

# Python 3. PyQt4
I want to load the initial data from the file for the test calculation. In the file, the data is written as a list, i.e.:
[20, 8, 4]
There is a code that reads this data from the file and inserts it into the fields:

def on_open_isd (self):
        options = QtGui.QFileDialog.Options()
        self.fileName = QtGui.QFileDialog.getOpenFileName(self, "Открыть как", "ИД. Расчёт объёма.txt",
                                                           "Text Files (*.txt)", options=options)  
                  
        if self.fileName:
            self.readFile = open(self.fileName, 'r', encoding='utf-8')
            open_isd = self.readFile.read()
            self.readFile.close()
        open_isd = open_isd[1:-1].replace(' ','')
        open_isd = open_isd.split(',')  
        self.pole_a.setText(str(open_isd[0]))
        self.pole_b.setText(str(open_isd[1]))
        self.pole_h.setText(str(open_isd[2]))

However, I don't like this approach. I would like to immediately extract the variable from the file in the form of a list, so that I do not have to translate into the python language.
1) Ideally, it would be possible to connect the module through a dialog box, but this method is not familiar to me. As far as I understand it doesn't exist.
2) How can I improve the function given by me in this version.
3) And also if there is more than one list in the file?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Q
qlkvg, 2017-02-28
@Pyrym

import ast
ast.literal_eval("[20, 8, 4]")

If there is more than one list, then it all depends on the record format. Most likely at first it is necessary to parse as the regular text.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question