Python PyQt5.QtWidgets.QFileDialog.getSaveFileName() Examples

The following are 30 code examples of PyQt5.QtWidgets.QFileDialog.getSaveFileName(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PyQt5.QtWidgets.QFileDialog , or try the search function .
Example #1
Source File: menu_file.py    From ocelot with GNU General Public License v3.0 7 votes vote down vote up
def dialog_save_lattice(self):
        """Save lattice to file"""

        filename = QFileDialog.getSaveFileName(self.mw, 'Save Lattice', '', "Python Files (*.py);;All Files (*)", options=QFileDialog.DontUseNativeDialog)
        if filename[0] == '':
            return 0

        lp = Parser()
        lines = lp.gui_lattice2input(self.mw.lattice, split=True)

        if filename[1] == 'Python Files (*.py)' and filename[0][-3:] != '.py':
            filename = filename[0] + '.py'
        else:
            filename = filename[0]

        with open(filename, 'w') as fp:
            fp.writelines(lines) 
Example #2
Source File: uamodeler.py    From opcua-modeler with GNU General Public License v3.0 7 votes vote down vote up
def _save_as(self):
        path, ok = QFileDialog.getSaveFileName(self.modeler, caption="Save OPC UA XML", filter="XML Files (*.xml *.XML)")
        if ok:
            print("PATH", path)
            if self._last_model_dir != os.path.dirname(path):
                self._last_model_dir = os.path.dirname(path)
                self.settings.setValue("last_model_dir", self._last_model_dir)
            self._model_mgr.save_xml(path)
            path = self._model_mgr.save_ua_model(path)
            self.modeler.update_recent_files(path) 
Example #3
Source File: anchor_position_dialog.py    From crazyflie-clients-python with GNU General Public License v2.0 6 votes vote down vote up
def _save_button_clicked(self):
        anchor_positions = self._data_model.get_anchor_postions()
        data = {}
        for id, pos in anchor_positions.items():
            data[id] = {'x': pos[0], 'y': pos[1], 'z': pos[2]}

        names = QFileDialog.getSaveFileName(self, 'Save file',
                                            self._current_folder,
                                            "*.yaml;;*.*")

        if names[0] == '':
            return

        self._current_folder = os.path.dirname(names[0])

        if not names[0].endswith(".yaml") and names[0].find(".") < 0:
            filename = names[0] + ".yaml"
        else:
            filename = names[0]

        f = open(filename, 'w')
        with f:
            yaml.dump(data, f) 
Example #4
Source File: recovery.py    From gridsync with GNU General Public License v3.0 6 votes vote down vote up
def _export_plaintext_recovery(self, gateway):
        dest, _ = QFileDialog.getSaveFileName(
            self.parent,
            "Select a destination",
            os.path.join(
                os.path.expanduser("~"), gateway.name + " Recovery Key.json"
            ),
        )
        if not dest:
            return
        try:
            gateway.export(dest, include_rootcap=True)
        except Exception as e:  # pylint: disable=broad-except
            error(self.parent, "Error exporting Recovery Key", str(e))
            return
        self.done.emit(dest) 
Example #5
Source File: work_log.py    From Awesome-Python-Scripts with MIT License 6 votes vote down vote up
def save(self):
        """Save log to file."""
        home = str(Path.home())
        self.output = ""
        self.output = QFileDialog.getSaveFileName(self,
                                                  'Save file',
                                                  home,
                                                  "ReST files (*.rst)")

        if self.output[0] is not "":
            with open(self.output[0], 'w') as f:
                f.write(self.te.toPlainText())

            btMessage = f'File saved as {self.output[0]}.'
        else:
            btMessage = "Can't save. No file specified."
        self.systemtray_icon.showMessage(
            APP_NAME, btMessage, QIcon(ICON_PATH), 5000)
        self.statusBar().showMessage(btMessage) 
Example #6
Source File: settingsdialog.py    From lector with GNU General Public License v2.0 6 votes vote down vote up
def on_pbLog_clicked(self):
        """ Select file for logging error/output of Lector
        """
        fileFilter = self.tr("Log files (*.log);;All files (*);;")
        init_filename = self.ui.lnLog.text()
        if not init_filename:
            if (os.path.split(sys.executable)[1]).lower().startswith('python'):
                logPath = os.path.abspath(os.path.dirname(__file__))
            else:
                logPath =  os.path.abspath(os.path.dirname(sys.executable))
            init_filename = os.path.join(logPath, "lector.log")
        filename = str(QFileDialog.getSaveFileName(self,
                self.tr("Select file for log output..."),
                init_filename,
                fileFilter))
        if not filename:
            return
        else:
            self.ui.lnLog.setText(filename) 
Example #7
Source File: main_win.py    From BlindWatermark with GNU General Public License v3.0 6 votes vote down vote up
def on_pushButton_10_clicked(self):
        """
        恢复
        """
        ori_img = self.my_recovery_parameter.get('ori_img',None)
        attacked_img = self.my_recovery_parameter.get('attacked_img',None)
        if not ori_img:
            QMessageBox.warning(self,"警告",'未读取原图',QMessageBox.Ok)
        elif not attacked_img:
            QMessageBox.warning(self,"警告",'未读取受到攻击的图片',QMessageBox.Ok)
        else:
            outfile_path,_ = QFileDialog.getSaveFileName(self, '恢复图片', self.my_bwm_parameter.get('work_path','./'),"PNG (*.png);;All Files (*)")
            if outfile_path:
                rate = self.doubleSpinBox_3.value()
                self.recovery_thread = recovery(ori_img,attacked_img,outfile_path,rate)
                self.recovery_thread.finished.connect(self.recovery_thread.deleteLater)
                self.recovery_thread.num_of_good.connect(self.show_recovery)
                self.recovery_thread.start() 
Example #8
Source File: core.py    From Dwarf with GNU General Public License v3.0 6 votes vote down vote up
def dump_memory(self, file_path=None, ptr=0, length=0):
        if ptr == 0:
            ptr, inp = InputDialog.input_pointer(self._app_window)
        if ptr > 0:
            if length == 0:
                accept, length = InputDialog.input(
                    self._app_window, hint='insert length', placeholder='1024')
                if not accept:
                    return
                try:
                    if length.startswith('0x'):
                        length = int(length, 16)
                    else:
                        length = int(length)
                except:
                    return
            if file_path is None:
                r = QFileDialog.getSaveFileName(self._app_window, caption='Save binary dump to file')
                if len(r) == 0 or len(r[0]) == 0:
                    return
                file_path = r[0]
            data = self.read_memory(ptr, length)
            if data is not None and len(data) > 1:
                with open(file_path, 'wb') as f:
                    f.write(data[1]) 
Example #9
Source File: centralwidget.py    From autokey with GNU General Public License v3.0 6 votes vote down vote up
def on_save_log(self):
        file_name, _ = QFileDialog.getSaveFileName(  # second return value contains the used file type filter.
            self.window(),
            "Save log file",
            "",
            ""  # TODO: File type filter. Maybe "*.log"?
        )
        del _  # We are only interested in the selected file name
        if file_name:
            list_widget = self.listWidget  # type: QListWidget
            item_texts = (list_widget.item(row).text() for row in range(list_widget.count()))
            log_text = "\n".join(item_texts) + "\n"
            try:
                with open(file_name, "w") as log_file:
                    log_file.write(log_text)
            except IOError:
                logger.exception("Error saving log file")
            else:
                self.on_clear_log()  # Error log saved, so clear the previously saved entries 
Example #10
Source File: work_log.py    From Awesome-Scripts with MIT License 6 votes vote down vote up
def save(self):
        """Save log to file."""
        home = str(Path.home())
        self.output = ""
        self.output = QFileDialog.getSaveFileName(self,
                                                  'Save file',
                                                  home,
                                                  "ReST files (*.rst)")

        if self.output[0] is not "":
            with open(self.output[0], 'w') as f:
                f.write(self.te.toPlainText())

            btMessage = f'File saved as {self.output[0]}.'
        else:
            btMessage = "Can't save. No file specified."
        self.systemtray_icon.showMessage(
            APP_NAME, btMessage, QIcon(ICON_PATH), 5000)
        self.statusBar().showMessage(btMessage) 
Example #11
Source File: presets_ui.py    From linux-show-player with GNU General Public License v3.0 6 votes vote down vote up
def __export_presets(self):
        names = [item.text() for item in self.presetsList.selectedItems()]
        archive, _ = QFileDialog.getSaveFileName(
            self,
            directory='archive.presets',
            filter='*.presets'
        )

        if archive != '':
            if not archive.endswith('.presets'):
                archive += '.presets'
            try:
                export_presets(names, archive)
            except PresetExportError as e:
                QDetailedMessageBox.dcritical(
                    translate('Presets', 'Presets'),
                    translate('Presets', 'Cannot export correctly.'),
                    str(e),
                    parent=self
                ) 
Example #12
Source File: gui.py    From SickZil-Machine with GNU Affero General Public License v3.0 6 votes vote down vote up
def new_project(self, src_imgdir):
        '''
        create new project directory from src image directory to dst
        '''
        imgdir = src_imgdir.toLocalFile()
        p = Path(imgdir)
        default_projdir = str(
            p.with_name( consts.default_proj_name(p.name) )
        )

        projdir,_ = QFileDialog.getSaveFileName(
            caption=consts.config["new_project_dialog"]["caption"],
            directory=default_projdir,
            filter=consts.config["new_project_dialog"]["filter"]
        )

        new_projdir = state.new_project(imgdir, projdir)
        if new_projdir:
            self.set_project(new_projdir)
            return new_projdir

    #--------------------------------------------------- 
Example #13
Source File: DyStockTableWidget.py    From DevilYuan with MIT License 6 votes vote down vote up
def _saveAsAct(self):
        data = {}
        if not DyStockTableSelectDlg(data, '{0}保存'.format(self.getUniqueName())).exec_():
            return

        defaultFileName = '{0}.json' if data['all'] else '{0}_高亮.json'
        defaultFileName = defaultFileName.format(self.getUniqueName())

        defaultDir = DyCommon.createPath('Stock/User/Save/Strategy')
        fileName, _ = QFileDialog.getSaveFileName(None, '保存股票表', os.path.join(defaultDir, defaultFileName), "JSON files (*.json);;all files(*.*)", options=QFileDialog.DontUseNativeDialog)
        if fileName:
            self._saveAs(fileName, data['all']) 
Example #14
Source File: SimulatorDialog.py    From urh with GNU General Public License v3.0 5 votes vote down vote up
def on_btn_save_transcript_clicked(self):
        file_path = QFileDialog.getSaveFileName(self, "Save transcript", "", "Text file (*.txt)")

        if file_path[0] == "":
            return

        transcript = self.ui.textEditTranscript.toPlainText()

        try:
            with open(str(file_path[0]), "w") as f:
                f.write(transcript)
        except Exception as e:
            QMessageBox.critical(self, "Error saving transcript", e.args[0]) 
Example #15
Source File: main.py    From PyQt5-Apps with GNU General Public License v3.0 5 votes vote down vote up
def exportDataAsCSV(self):
        # filename, filetype = QtWidgets.QFileDialog.getSaveFileName(None, 'Save File', '.', "All Files (*);;Text Files (*.txt)")
        if db:
            filename, filetype = QFileDialog.getSaveFileName(None, 'Save File', self.outPath, "CSV Files (*.csv)")
            if filename:
                print(filename)
                try:
                    num = cursor.execute(outSql % filename)
                    if num:
                        # self.messageBox("data has been exported as %s", % (filename) )
                        self.messageBox("data has been exported as %s!" % filename)
                except Exception as e:
                    self.messageBox("export data failed!\nerror msg: %s"%(e.args[1]))
        else:
            self.messageBox("connect to the database first!\nclick the button 'File-connect'") 
Example #16
Source File: gui.py    From PUBGIS with GNU General Public License v3.0 5 votes vote down vote up
def _select_output_file(self):
        file_name, _ = QFileDialog.getSaveFileName(directory=self.last_output_file_dir,
                                                   filter="Images (*.jpg)")
        self._set_output_file(file_name)

    # LIVE SECTION 
Example #17
Source File: main_win.py    From BlindWatermark with GNU General Public License v3.0 5 votes vote down vote up
def on_pushButton_3_clicked(self):
        """
        Slot documentation goes here.
        """
        if self.pushButton_3.text()=='嵌入':
            if bool(self.my_bwm_parameter.get('ori_img',False)) and bool(self.my_bwm_parameter.get('wm',False)):
                self.refresh_parameter()
                if self.my_bwm_parameter['mod'] <0.01:
                    QMessageBox.warning(self,"警告",'第一个量化因子:{}不符合要求'.format(self.my_bwm_parameter['mod']),QMessageBox.Ok)
                else:
                    my_file_path,_ = QFileDialog.getSaveFileName(self, '保存图片', self.my_bwm_parameter.get('work_path','./'),"PNG (*.png);;JPG (*.jpg);;All Files (*)")
                    if my_file_path:
                        self._thread = bwm_embed_thread(self.my_bwm_parameter,my_file_path)
                        self._thread.finished.connect(self._thread.deleteLater)
                        self._thread.finish_out.connect(self.bwm_add_item)
                        self._thread.assert_ERROR.connect(self.assert_error)
                        self._thread.valueChanged.connect(self.BlueProgressBar.setValue)
                        self._thread.start()
            else:
                QMessageBox.warning(self,"警告",'你需要打开原始图片和水印图片,才能进行嵌入',QMessageBox.Ok)
        elif self.pushButton_3.text()=='提取':
            if bool(self.my_bwm_parameter.get('ori_img',False)):
                self.refresh_parameter()
                if self.my_bwm_parameter['mod'] <0.01:
                    QMessageBox.warning(self,"警告",'第一个量化因子:{}不符合要求'.format(self.my_bwm_parameter['mod']),QMessageBox.Ok)
                elif self.my_bwm_parameter['wm_shape'][0] == 0 or self.my_bwm_parameter['wm_shape'][1] == 0:
                    QMessageBox.warning(self,"警告",'提取时需要设定水印形状',QMessageBox.Ok)
                else:
                    my_file_path,_ = QFileDialog.getSaveFileName(self, '保存图片', self.my_bwm_parameter.get('work_path','./'),"PNG (*.png);;JPG (*.jpg);;All Files (*)")
                    if my_file_path:
                        self._thread = bwm_extract_thread(self.my_bwm_parameter,my_file_path)
                        self._thread.finished.connect(self._thread.deleteLater)
                        self._thread.finish_out.connect(self.bwm_add_item)
                        self._thread.valueChanged.connect(self.BlueProgressBar.setValue)
                        self._thread.start()
            else:
                QMessageBox.warning(self,"警告",'你需要打开要提取水印的图片,才能进行提取',QMessageBox.Ok) 
Example #18
Source File: dps_GUI_program.py    From DPS5005_pyGUI with GNU General Public License v3.0 5 votes vote down vote up
def file_save(self):
		filename, _ = QFileDialog.getSaveFileName(self, "Save File", datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S")+".csv", "All Files (*);; CSV Files (*.csv)")
		if filename != '':
			rows = zip(self.graph_X, self.graph_Y1, self.graph_Y2)
			
			if sys.platform.startswith('win'):
				with open(filename, 'w', newline='') as f:					# added newline to prevent additional carriage return in windows (\r\r\n)
					writer = csv.writer(f)
					row = ['time(s)','voltage(V)','current(A)']
					writer.writerow(row)
					for row in rows:
						writer.writerow(row)
			elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
				with open(filename, 'w') as f:					# added newline to prevent additional carriage return in windows (\r\r\n)
					writer = csv.writer(f)
					row = ['time(s)','voltage(V)','current(A)']
					writer.writerow(row)
					for row in rows:
						writer.writerow(row)
			elif sys.platform.startswith('darwin'):
				with open(filename, 'w') as f:					# added newline to prevent additional carriage return in windows (\r\r\n)
					writer = csv.writer(f)
					row = ['time(s)','voltage(V)','current(A)']
					writer.writerow(row)
					for row in rows:
						writer.writerow(row)
			else:
				raise EnvironmentError('Unsupported platform')
			
			
			
		#	with open(filename, 'w', newline='') as f:					# added newline to prevent additional carriage return in windows (\r\r\n)
		#		writer = csv.writer(f)
		#		row = ['time(s)','voltage(V)','current(A)']
		#		writer.writerow(row)
		#		for row in rows:
		#			writer.writerow(row)
		
#--- thread related code 
Example #19
Source File: settingsdialog.py    From lector with GNU General Public License v2.0 5 votes vote down vote up
def on_pushButtonPWL_clicked(self):
        filename = str(QFileDialog.getSaveFileName(self,
                self.tr("Select your private dictionary"),
                self.ui.lineEditPWL.text(),
                self.tr("Dictionary (*.txt *.dic);;All files (*);;")
                ))
        if not filename:
            return
        else:
            self.ui.lineEditPWL.setText(filename) 
Example #20
Source File: DyStockTableWidget.py    From DevilYuan with MIT License 5 votes vote down vote up
def _export2JqkaAct(self):
        data = {}
        if not DyStockTableSelectDlg(data, '{0}导出到同花顺'.format(self.getUniqueName())).exec_():
            return

        defaultFileName = '{0}.sel' if data['all'] else '{0}_高亮.sel'
        defaultFileName = defaultFileName.format(self.getUniqueName())

        defaultDir = DyCommon.createPath('Stock/User/Save/Strategy/同花顺')
        fileName, _ = QFileDialog.getSaveFileName(None, '导出到同花顺', os.path.join(defaultDir, defaultFileName), "同花顺files (*.sel);;all files(*.*)", options=QFileDialog.DontUseNativeDialog)
        if fileName:
            self.export2Jqka(fileName) 
Example #21
Source File: MCUProg.py    From JMCUProg with MIT License 5 votes vote down vote up
def on_btnRead_finished(self):
        binpath, filter = QFileDialog.getSaveFileName(caption=u'将读取到的数据保存到文件', filter=u'程序文件 (*.bin)')
        if binpath:
            with open(binpath, 'wb') as f:
                f.write(bytes(self.buff))

        self.jlk.reset()

        self.setEnabled(True)
        self.prgInfo.setVisible(False) 
Example #22
Source File: SimulatorDialog.py    From urh with GNU General Public License v3.0 5 votes vote down vote up
def on_btn_save_log_clicked(self):
        file_path = QFileDialog.getSaveFileName(self, "Save log", "", "Log file (*.log)")

        if file_path[0] == "":
            return

        log_string = self.ui.textEditSimulation.toPlainText()

        try:
            with open(str(file_path[0]), "w") as f:
                f.write(log_string)
        except Exception as e:
            QMessageBox.critical(self, "Error saving log", e.args[0]) 
Example #23
Source File: MCUProg.py    From DMCUProg with MIT License 5 votes vote down vote up
def on_btnRead_finished(self):
        binpath, filter = QFileDialog.getSaveFileName(caption='将读取到的数据保存到文件', filter='程序文件 (*.bin)')
        if binpath:
            with open(binpath, 'wb') as f:
                f.write(bytes(self.buff))

        self.dap.reset()
        self.daplink.close()
        
        self.setEnabled(True)
        self.prgInfo.setVisible(False) 
Example #24
Source File: fileManager.py    From openMotor with GNU General Public License v3.0 5 votes vote down vote up
def showSaveDialog(self):
        path = QFileDialog.getSaveFileName(None, 'Save motor', '', 'Motor Files (*.ric)')[0]
        if path == '' or path is None:
            return None
        if path[-4:] != '.ric':
            path += '.ric'
        return path

    # Checks if a motor's propellant is in the library, adds it if it isn't, and also looks for conflicts 
Example #25
Source File: converter.py    From openMotor with GNU General Public License v3.0 5 votes vote down vote up
def showFileSelector(self):
        """Open a dialog to pick the file to save to"""
        path = QFileDialog.getSaveFileName(None, 'Export ' + self.name, '', self.getFileTypeString())[0]
        if path == '' or path is None:
            return
        if not any([path.endswith(ext) for ext in self.fileTypes.keys()]):
            path += list(self.fileTypes.keys())[0] # if they didn't specify a file type, just pick one
        return path 
Example #26
Source File: DyStockTableWidget.py    From DevilYuan with MIT License 5 votes vote down vote up
def _export2JqkaAct(self):
        data = {}
        if not DyStockTableSelectDlg(data, '{0}导出到同花顺'.format(self.getUniqueName())).exec_():
            return

        defaultFileName = '{0}.sel' if data['all'] else '{0}_高亮.sel'
        defaultFileName = defaultFileName.format(self.getUniqueName())

        defaultDir = DyCommon.createPath('Stock/User/Save/Strategy/同花顺')
        fileName, _ = QFileDialog.getSaveFileName(self, '导出到同花顺', os.path.join(defaultDir, defaultFileName), "同花顺files (*.sel);;all files(*.*)")
        if fileName:
            self.export2Jqka(fileName) 
Example #27
Source File: DyStockTableWidget.py    From DevilYuan with MIT License 5 votes vote down vote up
def _saveAsAct(self):
        data = {}
        if not DyStockTableSelectDlg(data, '{0}保存'.format(self.getUniqueName())).exec_():
            return

        defaultFileName = '{0}.json' if data['all'] else '{0}_高亮.json'
        defaultFileName = defaultFileName.format(self.getUniqueName())

        defaultDir = DyCommon.createPath('Stock/User/Save/Strategy')
        fileName, _ = QFileDialog.getSaveFileName(self, '保存股票表', os.path.join(defaultDir, defaultFileName), "JSON files (*.json);;all files(*.*)")
        if fileName:
            self._saveAs(fileName, data['all']) 
Example #28
Source File: Ui_MakupGUI.py    From AIMakeup with Apache License 2.0 5 votes vote down vote up
def _save(self):
        output_path,_=QFileDialog.getSaveFileName(self.centralWidget,'选择保存位置','./','Image Files(*.png *.jpg *.bmp)')
        if output_path:
            self.save(output_path,self.im_bgr)
        else:
            QMessageBox.warning(self.centralWidget,'无效路径','无效路径,请重新选择!') 
Example #29
Source File: Ui_MakupGUI.py    From AIMakeup with Apache License 2.0 5 votes vote down vote up
def _save_compare(self):
        output_path,_=QFileDialog.getSaveFileName(self.centralWidget,'选择保存位置','./','Image Files(*.png *.jpg *.bmp)')
        if output_path:
            self.save(output_path,np.concatenate([self.im_ori,self.im_bgr],1))
        else:
            QMessageBox.warning(self.centralWidget,'无效路径','无效路径,请重新选择!') 
Example #30
Source File: qt.py    From pywebview with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_file_dialog(self, dialog_type, directory, allow_multiple, save_filename, file_filter):
        if dialog_type == FOLDER_DIALOG:
            self._file_name = QFileDialog.getExistingDirectory(self, localization['linux.openFolder'], options=QFileDialog.ShowDirsOnly)
        elif dialog_type == OPEN_DIALOG:
            if allow_multiple:
                self._file_name = QFileDialog.getOpenFileNames(self, localization['linux.openFiles'], directory, file_filter)
            else:
                self._file_name = QFileDialog.getOpenFileName(self, localization['linux.openFile'], directory, file_filter)
        elif dialog_type == SAVE_DIALOG:
            if directory:
                save_filename = os.path.join(str(directory), str(save_filename))

            self._file_name = QFileDialog.getSaveFileName(self, localization['global.saveFile'], save_filename)

        self._file_name_semaphore.release()