PyQt学习笔记-打开文件并从中读取数据

打开文本文件txt,从中读取数据

@pyqtSlot()
    def on_menu_files_open_triggered(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        print("打开")
        my_file_path = QFileDialog.getOpenFileName(self, "打开文件", "/", "*.txt")
        print(my_file_path)
        f = open(my_file_path[0], "r", encoding="utf-8")
        my_data = f.read()
        f.close()
        self.textBrowser.append(my_data)

注意

1 QFileDialog.getOpenFileName 传出的是一个(str,str)元组
2 此处打开文件时,一定要注意编码格式,为UTF-8

此时,发现打开文件后,弹出的文件对话框没有关闭
解决办法:

 @pyqtSlot()
        def on_menu_files_open_triggered(self):
                """
				Slot documentation goes here.
				"""
                # TODO: not implemented yet
                print("打开")
                dialog = QFileDialog()
                my_file_path = dialog.getOpenFileName(self, "打开文件", "/", "*.txt")
                print(my_file_path)
                f = open(my_file_path[0], "r", encoding="utf-8")
                my_data = f.read()
                f.close()
                self.textBrowser.append(my_data)

将文本框内容保存到文本

注意:在使用open时,一定要注意参数和编码方式

@pyqtSlot()
        def on_menu_files_save_triggered(self):
                """
				Slot documentation goes here.
				"""
                # TODO: not implemented yet
                print("保存")
                my_data = self.textBrowser.toPlainText()
                dialog_save = QFileDialog()
                my_file = dialog_save.getSaveFileName(self, "文件另存为", "/")
                print(my_file)
                f = open(my_file[0], "w", encoding="utf-8")
                f.write(my_data)
                f.close()

你可能感兴趣的:(PyQt)