在PyQt中读取文件

时间:2017-01-20 14:22:18

标签: python pyqt4 qstring qfiledialog

我正在PyQt4中构建一个程序,它要求从多个文本文件中提取数据。我有一个按钮,可以选择文件:它的代码是

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_())

按下按钮时,我可以选择我需要的文本文件,但是我无法阅读它们?当我要求它在日志中打印文件名时,它会给我<PyQt4.QtCore.QStringList object at 0x0000000002BD0BA8>

我也尝试过:

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

但是这会给IOError: [Errno 22] invalid mode ('r') or filename: '<PyQt4.QtCore.QStringList object at 0x0000000002F00BA8>,所以如何让QStringList object可读?

1 个答案:

答案 0 :(得分:2)

QtGui.QFileDialog.getOpenFileNames(...)会返回一个字符串列表,因此您无法打开并加载它,您必须逐个执行此操作。

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)