Charlietrypsin
Charlietrypsin

Reputation: 107

Reading files in PyQt

I am building a program in PyQt4 and it requires that data be pulled from multiple text files. I have a button which will select files: it's code being

qtCreatorFile = 'parser.ui'

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self.file_selector.clicked.connect(self.File_Selector)

        self.log

    def File_Selector(self):
        files_list = []
        filenames = str(QFileDialog.getOpenFileNames(self, "Select File", "", "*.txt"))
        self.log.insertPlainText('Loading files ' + '\n')
        self.log.insertPlainText(filenames + '\n')

if __name__ == "__main__":
        app = QtGui.QApplication(sys.argv)
        window = MyApp()
        window.show()
        sys.exit(app.exec_())

When the button is pressed I can select the text files I need, but I'm not able to read them? When I ask it to print the filenames in the log it gives me <PyQt4.QtCore.QStringList object at 0x0000000002BD0BA8>

I also tried:

    text = open(filenames).read()
    self.log.insertPlainText(text)

But that gives IOError: [Errno 22] invalid mode ('r') or filename: '<PyQt4.QtCore.QStringList object at 0x0000000002F00BA8> so how do I make the QStringList object readable?

Upvotes: 1

Views: 5151

Answers (1)

eyllanesc
eyllanesc

Reputation: 244282

QtGui.QFileDialog.getOpenFileNames(...) returns a string list, so you can not open it and load it, you have to do it one by one.

def File_Selector(self):
    filenames = QtGui.QFileDialog.getOpenFileNames(self, "Select File", "", "*.txt")
    self.log.insertPlainText('Loading files ' + '\n')
    self.log.insertPlainText(str(filenames) + '\n')
    for filename in filenames:
        text = open(filename).read()
        self.log.insertPlainText(text)

Upvotes: 3

Related Questions