def getOpenFileNamesAndFilter(parent=None, caption="", directory="", filter="", initialFilter="", options=QFileDialog.Options()): """ Module function to get a list of names of files for opening and the selected file name filter. @param parent parent widget of the dialog (QWidget) @param caption window title of the dialog (string) @param directory working directory of the dialog (string) @param filter filter string for the dialog (string) @param initialFilter initial filter for the dialog (string) @param options various options for the dialog (QFileDialog.Options) @return list of file names to be opened and selected filter (list of string, string) """ if Globals.isLinuxPlatform(): options |= QFileDialog.DontUseNativeDialog newfilter = __reorderFilter(filter, initialFilter) if PYQT_VERSION_STR >= "5.0.0": return QFileDialog.getOpenFileNames( parent, caption, directory, newfilter, initialFilter, options) else: return QFileDialog.getOpenFileNamesAndFilter( parent, caption, directory, newfilter, initialFilter, options)
def open_file(self, filename='', cursorPosition=-1, tabIndex=None, positionIsLineNumber=False, notStart=True): if not filename: if settings.WORKSPACE: directory = settings.WORKSPACE else: directory = os.path.expanduser("~") editorWidget = self.get_actual_editor() pexplorer = self._parent.explorer current_project = pexplorer and pexplorer.get_actual_project() if current_project is not None: directory = current_project elif editorWidget is not None and editorWidget.ID: directory = file_manager.get_folder(editorWidget.ID) extensions = ';;'.join( ['(*%s)' % e for e in settings.SUPPORTED_EXTENSIONS + ['.*', '']]) fileNames = QFileDialog.getOpenFileNames(self, _translate("_s_MainContainer", "Open File"), directory, extensions)[0]#list() else: fileNames = [filename] #print(":::filename:", filename) if not fileNames: return othersFileNames = [] for filename in fileNames: if QFileInfo(filename).isDir(): othersFileNames.extend( QFileDialog.getOpenFileNames(None, "Select files", filename, "Files (*.*)")[0] ) elif file_manager.get_file_extension(filename) in ('jpg', 'png'): self.open_image(filename) elif file_manager.get_file_extension(filename).endswith('ui'): self.w = uic.loadUi(filename) self.w.show() else: self.__open_file(filename, cursorPosition, tabIndex, positionIsLineNumber, notStart) for filename in othersFileNames: print("fileNames:::", filename) if QFileInfo(filename).isDir(): continue elif file_manager.get_file_extension(filename) in ('jpg', 'png'): self.open_image(filename) elif file_manager.get_file_extension(filename).endswith('ui'): self.w = uic.loadUi(filename) self.w.show() else: self.__open_file(filename, cursorPosition, tabIndex, positionIsLineNumber, notStart)
def on_addBtn_clicked(self): fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files", '', "Files (*.txt);;All Files (*)") #self.fileDicts.clear() #self.fileView.setRowCount(0) #fileNames.sort() row = len(self.fileDicts) for fileName in fileNames: txtName = QFileInfo(fileName).baseName() with open(fileName, 'r') as f : content = f.read() contents = [] contents = content.split(" ") fileDict = {} fileDict['content'] = content fileDict['filename'] = txtName fileDict['group'] = txtName[0:-2] fileDict['count'] = len(contents) fileDict['seq'] = str(row) self.fileDicts['seq_' + str(row).zfill(4)] = fileDict row += 1 #self.nTotal = row self.updateFileDict() self.nStart = 0 self.nextBtn.setEnabled(True) self.preBtn.setEnabled(False) self.updateTableUi()
def addSongFile(self): urls, _ = QFileDialog.getOpenFileNames( caption="Select one or more files to open", directory="/home", filter="music(*mp2 *.mp3 *.mp4 *.m4a *wma *wav)") if urls: self.addSongFiles(urls)
def addImage(self): fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Images", '', "Images (*.png *.xpm *.jpg);;All Files (*)") for fileName in fileNames: row = self.imagesTable.rowCount() self.imagesTable.setRowCount(row + 1) imageName = QFileInfo(fileName).baseName() item0 = QTableWidgetItem(imageName) item0.setData(Qt.UserRole, fileName) item0.setFlags(item0.flags() & ~Qt.ItemIsEditable) item1 = QTableWidgetItem("Normal") item2 = QTableWidgetItem("Off") if self.guessModeStateAct.isChecked(): if '_act' in fileName: item1.setText("Active") elif '_dis' in fileName: item1.setText("Disabled") elif '_sel' in fileName: item1.setText("Selected") if '_on' in fileName: item2.setText("On") self.imagesTable.setItem(row, 0, item0) self.imagesTable.setItem(row, 1, item1) self.imagesTable.setItem(row, 2, item2) self.imagesTable.openPersistentEditor(item1) self.imagesTable.openPersistentEditor(item2) item0.setCheckState(Qt.Checked)
def choose_tracks(self): chosen = QFileDialog.getOpenFileNames(parent=self.window, directory=os.getenv('HOME'), caption="Open one or more tracks") tracks = chosen[0] count = len(tracks) start_all = time.time() for track in tracks: is_audio = False is_video = False for a in audio_files: if track.lower().endswith(a): is_audio = True break for v in video_files: if track.lower().endswith(v): is_video = True break if is_audio: queue.put(track) # Adds it directly, bypassing threading (doesn't play nice) elif is_video: self.process_track(track) # The track wasn't a playable track at all! else: count -= 1 self.start_working(start_all, count)
def load_fonts(self): """ Load fonts from a directory, and sets appropriate options :return: """ f_f = QFileDialog.getOpenFileNames(self, "Load Fonts", "", "Font Files (*.ttf *.otf)") if f_f[0]: for f_label, f_style in zip(self.fnt_file_name_list, self.fnt_sty_combo_list): f_label.setText("Load font file...") f_style.setCurrentIndex(SEL_NONE) f_style.setEnabled(False) self.font_files = f_f[0] f_f_names = [] for file in self.font_files: file = os.path.normpath(file) base, fn = os.path.split(file) f_f_names.append(fn) for f_file, f_label, f_style in zip(f_f_names, self.fnt_file_name_list, self.fnt_sty_combo_list): f_label.setText(f_file) f_style.setEnabled(True) if "regular" in f_file.lower(): f_style.setCurrentIndex(SEL_REGULAR) elif "bold" in f_file.lower() and "italic" in f_file.lower(): f_style.setCurrentIndex(SEL_BOLDITALIC) elif "bold" in f_file.lower(): f_style.setCurrentIndex(SEL_BOLD) elif "italic" in f_file.lower(): f_style.setCurrentIndex(SEL_ITALIC) if self.new_fnt_name.text(): self.gen_ttf_btn.setEnabled(True)
def getOpenFileNames( parent=None, caption="", directory="", filter="", selectedFilter="", options=OldFileDialog.Options() ): path, _ = OldFileDialog.getOpenFileNames(parent, caption, directory, filter, selectedFilter, options) if path: path = os.path.normpath(path) return path, _
def appenditems_src(self, qtree): # 扩展名筛选 fileext_video = config.fileext_video fileext_subtitle = config.fileext_subtitle filter_video = " ".join(["*." + x for x in fileext_video]) filter_subtitle = " ".join(["*." + x for x in fileext_subtitle]) filter_video_sub = " ".join([filter_video, filter_subtitle]) filedialog_filter = "视频与字幕 ({});;视频 ({});;字幕 ({})".format( filter_video_sub, filter_video, filter_subtitle) # 获取文件列表 filelist = QFileDialog.getOpenFileNames(self, "选择原始文件", config.filedialog_lastdir, filedialog_filter)[0] if len(filelist) > 0: config.filedialog_lastdir = os.path.dirname(filelist[0]) filelist = [x for x in filelist if os.path.isfile(x)] # 显示文件列表 filelist_subtitle = [] for i in reversed(range(len(filelist))): if os.path.splitext(filelist[i])[1][1:] in fileext_subtitle: filelist_subtitle.insert(0, filelist.pop(i)) items = self.qtreewidegt_getitems(qtree) for filename in filelist: if filename not in items: items[filename] = set() for subtitle in filelist_subtitle: for video in items: if subtitle.startswith(os.path.splitext(video)[0]): items[video].add(subtitle) break self.qtreewidegt_setitems(qtree, items) qtree.resizeColumnToContents(0)
def getImageFileNamesToOpen(cls, parent_window, defaultDirectory): """ opens a QFileDialog for importing files """ extensions = ['nn'] filter_strs = ["*." + x for x in extensions] filters = ["{filt} ({filt})".format(filt=x) for x in filter_strs] filt_all_str = "Image files (" + ' '.join(filter_strs) + ')' fileNames = [] if ilastik_config.getboolean("ilastik", "debug"): # use Qt dialog in debug mode (more portable?) file_dialog = QFileDialog(parent_window, "Select Model") file_dialog.setOption(QFileDialog.DontUseNativeDialog, True) # do not display file types associated with a filter # the line for "Image files" is too long otherwise file_dialog.setNameFilters([filt_all_str] + filters) #file_dialog.setNameFilterDetailsVisible(False) # select multiple files file_dialog.setFileMode(QFileDialog.ExistingFiles) file_dialog.setDirectory(defaultDirectory) if file_dialog.exec_(): fileNames = file_dialog.selectedFiles() else: # otherwise, use native dialog of the present platform fileNames, _ = QFileDialog.getOpenFileNames(parent_window, "Select Model", defaultDirectory, filt_all_str) return fileNames
def openFileNamesDialog(app): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog files, _ = QFileDialog.getOpenFileNames( app, "QFileDialog.getOpenFileNames()", "", "All Files (*);;Python Files (*.py)", options=options) if files: logger.debug(files) return files
def on_add_torrent_browse_file(self): filenames = QFileDialog.getOpenFileNames( self, "Please select the .torrent file", "", "Torrent files (*.torrent)") if not filenames[0]: return for filename in filenames[0]: self.add_torrent_to_channel(filename)
def on_browse_clicked(self): """ Will open a dialog to browse for files """ if self.defaultPath is None: self.fileNames = QFileDialog.getOpenFileNames(self, "Select Measurement Files", filter=("MDF file (*.dat *.mdf *.mf4 *.mfx *.mfxz)"))[0] self.defaultPath = dirname(str(self.fileNames[0])) else: self.fileNames = QFileDialog.getOpenFileNames(self, "Select Measurement Files", self.defaultPath, filter=("MDF file (*.dat *.mdf *.mf4 *.mfx *.mfxz)"))[0] if not len(self.fileNames) == 0: self.FileList.addItems(self.fileNames) self.mdfinfoClass.__init__() self.cleanChannelList() self.cleanSelectedChannelList() ChannelList = convertChannelList(self.mdfinfoClass.listChannels(str(self.fileNames[0]))) self.SelectedChannelList.addItems(ChannelList) self.FileList.item(0).setSelected(True)
def from_files(self): gallery_list = QFileDialog.getOpenFileNames(self, 'Select 1 or more gallery to add', filter='Archives (*.zip *.cbz)') for path in gallery_list[0]: #Warning: will break when you add more filters if len(path) != 0: self.add_gallery(path, os.path.split(path)[1])
def chooseFile(self): "Load a single image" exts = "" for i in self.supportedExts: exts += "*"+i+" " # QFileDialog only accepts a string like this: "*.jpg *.png" files, _ = QFileDialog.getOpenFileNames(self.parentWidget(), "Select image", filter=exts) if files: # if a file was chosen self.imagesSelected.emit(files)
def on_add_torrent_browse_file(self): filenames = QFileDialog.getOpenFileNames(self, "Please select the .torrent file", QDir.homePath(), "Torrent files (*.torrent)") if len(filenames[0]) > 0: [self.pending_uri_requests.append(u"file:%s" % filename) for filename in filenames[0]] self.process_uri_request()
def get_open_file_names(*args, **kwargs): filenames = [] names, _selected_filter = QFileDialog.getOpenFileNames(*args, **kwargs) for filename in names: filenames.append(QDir.toNativeSeparators(filename)) return filenames
def on_add_mdblob_browse_file(self): filenames = QFileDialog.getOpenFileNames(self, "Please select the .mdblob file", QDir.homePath(), "Tribler metadata files (*.mdblob)") if len(filenames[0]) > 0: for filename in filenames[0]: self.pending_uri_requests.append(u"file:%s" % filename) self.process_uri_request()
def add_musics(self): self.files = QFileDialog.getOpenFileNames(self, "选择音乐文件", self.downloadDir, self.tr("*.mp3"))[0] if not self.files: return self.exec_add_operation(self.files) self.musics_added_signal.emit(True) for item in self.files: row = self.playlist.get_item_index(item) self.setRangeSelected(QTableWidgetSelectionRange(row, 0, row, self.columnCount()-1), True)
def import_files(self): """ Import selected files to xmms library :param self: :return: None """ for file_with_path in QFileDialog.getOpenFileNames(self, "Import files to Xmms", os.path.expanduser("~"), ""): for filename in file_with_path: if os.path.isfile(filename): xmmsfun.xmms_import_file(filename)
def open_file(self, current_index): filenames = [] file_types = '*mp3 *wma *wav *asf *aac *mp3pro *vqf *flac *ape *mid *ogg' \ ' *MP3 *WMA *WAV *ASF *AAC *MP3PRO *VQF *FLAC *APE *MID *OGG' if current_index == 0: filenames = QFileDialog.getOpenFileNames(self, '选择音乐文件', 'G:/', file_types)[0] elif current_index == 1: dir_path = QFileDialog.getExistingDirectory(self, '选择音乐文件', 'G:/') filenames = ['%s/%s' % (dir_path, file_name) for file_name in QDir(dir_path).entryList() if file_name != '.' and file_name != '..' and file_name.split('.')[-1] in file_types] self.__musicList.add_music_item(filenames)
def on_get_file_names_click(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog files, _ = QFileDialog.getOpenFileNames(self, 'QFileDialog.getOpenFileNames()', '', 'All Files(*);;Python Files(*.py)', options=options) if files: print(files)
def file_open(): filetypes = app.filetypes('.ly') caption = app.caption(_("dialog title", "Open File")) directory = app.basedir() files = QFileDialog.getOpenFileNames(None, caption, directory, filetypes)[0] if files: w = mainwindow() w.openUrls([QUrl.fromLocalFile(f) for f in files]) if not app.documents: w.cleanStart()
def setOpenFileNames(self): options = QFileDialog.Options() if not self.native.isChecked(): options |= QFileDialog.DontUseNativeDialog files, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", self.openFilesPath, "All Files (*);;Text Files (*.txt)", options=options) if files: self.openFilesPath = files[0] self.openFileNamesLabel.setText("[%s]" % ', '.join(files))
def open_files(self, mode): a = QFileDialog() if mode == 1: v = a.getOpenFileNames(caption="Импорт файлов rpm...", filter="RPM Files (*.rpm);;Any files (*.*)")[0] return json.dumps(v) elif mode == 2: directory = a.getExistingDirectory(options=QFileDialog.ShowDirsOnly)[0] return json.dumps(directory) elif mode == 3: return json.dumps(a.getOpenFileName()[0])
def openFile(self): supportedExtensions = ['.txt'] for markup in markups.get_all_markups(): supportedExtensions += markup.file_extensions fileFilter = ' (' + str.join(' ', ['*'+ext for ext in supportedExtensions]) + ');;' fileNames = QFileDialog.getOpenFileNames(self, self.tr("Select one or several files to open"), "", self.tr("Supported files") + fileFilter + self.tr("All files (*)")) for fileName in fileNames[0]: self.openFileWrapper(fileName)
def onOpenFile(self): ''' 打开窗口,选择命令文件,支持一次选择多个文件 ''' filepaths, _ = QFileDialog.getOpenFileNames( self, 'Open file', None, 'Command Files (*.cmd);;All Files (*)') if filepaths: for filepath in filepaths: filepath = os.path.normpath(filepath) self.handler.processFile(filepath)
def open_file(self): filename, _ = QFileDialog.getOpenFileNames(self, self.tr("Open Images"), os.path.expanduser("~"), "Images (*.png *.jpg *.bmp" " *.tif);;All Files (*)") # to handle cancel option if filename: self.inImage_name = filename[0] self.load_file() else: pass
def getOpenFileNames(parent=None, caption="", directory="", filter="", options=QFileDialog.Options()): """ Module function to get a list of names of files for opening. @param parent parent widget of the dialog (QWidget) @param caption window title of the dialog (string) @param directory working directory of the dialog (string) @param filter filter string for the dialog (string) @param options various options for the dialog (QFileDialog.Options) @return list of file names to be opened (list of string) """ if Globals.isLinuxPlatform(): options |= QFileDialog.DontUseNativeDialog if PYQT_VERSION_STR >= "5.0.0": return QFileDialog.getOpenFileNames( parent, caption, directory, filter, "", options)[0] else: return QFileDialog.getOpenFileNames( parent, caption, directory, filter, options)
def on_add_dictionaries(self): filters = ['*' + ext for ext in dictionary_formats] new_filenames = QFileDialog.getOpenFileNames( self, _('Add dictionaries'), None, _('Dictionary Files') + ' (%s)' % ' '.join(filters), )[0] dictionaries = list(self._dictionaries) for filename in new_filenames: if filename not in dictionaries: dictionaries.append(filename) self._update_dictionaries(dictionaries)
def convertFilesDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog if os.path.isdir(self.WSPPreferences['currentFilePath']): path = self.WSPPreferences['currentFilePath'] else: path = '' filename, _ = QFileDialog.getOpenFileNames( self, "QFileDialog.getOpenFileNames()", path, "All Files (*);;Python Files (*.py)", options=options) if filename: if len(filename) > 1: multiple_files = True else: multiple_files = False currentFilePath, currentFileName = os.path.split(filename[0]) self.WSPPreferences['currentFilePath'] = currentFilePath self.WSPPreferences['currentFileName'] = currentFileName if os.path.isdir(self.WSPPreferences['currentFilePath']): path = self.WSPPreferences['currentFilePath'] else: path = '' filename, ok = QFileDialog.getSaveFileName( self, "Save file", path, "All Files (*);;Text Files (*.txt)", options=options) if ok: futureFilePath, futureFileName = os.path.split(filename) futureFileNameSplitted = futureFileName.split('.') if futureFileNameSplitted[-1] != 'h5': futureFileName = futureFileName + '.h5' # ask for group name text, ok = QInputDialog.getText(self, 'Group name', 'Enter the group name:') if ok: self.WSPPreferences['currentGroupName'] = text # ask for ExperimentType text, ok = QInputDialog.getText( self, 'Experiment type', 'Enter the experiment type:') if ok: self.filePreferences['ExperimentType'] = text self.statusBar().showMessage( 'Opening: ' + self.WSPPreferences['currentFileName']) self.FM.Read_Experiment_File(filepath = self.WSPPreferences['currentFilePath'],\ filename = self.WSPPreferences['currentFileName'],\ read_multiple_files = multiple_files) self.statusBar().showMessage('Saving ' + futureFileName) self.FM.Write_Experiment_to_h5(filepath = futureFilePath,\ filename = futureFileName, \ group_name = self.WSPPreferences['currentGroupName'], \ force_overwrite = True, ExperimentType = self.filePreferences['ExperimentType']) self.statusBar().showMessage(futureFileName + ' saved.') self.WSPPreferences['currentFilePath'] = futureFilePath self.WSPPreferences['currentFileName'] = futureFileName
def openFileChooser(self): files, _ = QFileDialog.getOpenFileNames( self, "Schnittmusterdateien aussuchen", "", "PDF Dateien (*.pdf)") for path in files: self.file_list.addItem(path)
def load_project(self): path = config.get_key('paths', 'project_start') if path == 'None': file_names, _ = QFileDialog.getOpenFileNames( None, 'Load Project File (*.kmap)') else: start_path = str(__directory__ / path) file_names, _ = QFileDialog.getOpenFileNames( None, 'Load Project File (*.kmap)', str(start_path)) if not file_names: return file_path = file_names[0] # save = pickle.load(open(file_path, 'rb')) save = self.decompress_pickle(file_path) data_tabs = [tab_save for tab_save in save if tab_save[1][0] in ['SlicedDataTab', 'OrbitalDataTab']] basic_tabs = [tab_save for tab_save in save if tab_save[1][0] not in ['LMFitPlotTab', 'LMFitTab', 'LMFitResultTab', 'SlicedDataTab', 'OrbitalDataTab', 'SplitViewTab']] lmfit_tabs = [tab_save for tab_save in save if tab_save[1][0] == 'LMFitTab'] split_tabs = [tab_save for tab_save in save if tab_save[1][0] == 'SplitViewTab'] result_tabs = [tab_save for tab_save in save if tab_save[1][0] == 'LMFitResultTab'] plot_tabs = [tab_save for tab_save in save if tab_save[1][0] == 'LMFitPlotTab'] # Go through all non lmfit tabs first and replace the save # for a tab with the tab itself to be used for tabs that # depend on it for tab_save in basic_tabs: index, tab_save, _ = tab_save save[index] = self.tab_widget.open_tab_by_save( tab_save) ID_maps = [] for tab_save in data_tabs: index, tab_save, _ = tab_save tab, ID_map = self.tab_widget.open_tab_by_save( tab_save) save[index] = tab ID_maps.append(ID_map) for tab_save in lmfit_tabs: index, tab_save, dependencies = tab_save sliced_idx, orbital_idx = dependencies sliced_tab = save[sliced_idx] orbital_tab = save[orbital_idx] tab = self.tab_widget.open_tab_by_save(tab_save, sliced_tab, orbital_tab) tab.sliced_data_tab_idx = sliced_idx tab.orbital_data_tab_idx = orbital_idx save[index] = tab for tab_save in split_tabs: index, tab_save, dependencies = tab_save sliced_idx, orbital_idx = dependencies sliced_tab = save[sliced_idx] orbital_tab = save[orbital_idx] tab = self.tab_widget.open_tab_by_save(tab_save, sliced_tab, orbital_tab) save[index] = tab for tab_save in result_tabs: index, tab_save, dependencies = tab_save lmfit_tab_idx = dependencies[0] lmfit_tab = save[lmfit_tab_idx] tab = self.tab_widget.open_tab_by_save( tab_save, lmfit_tab, ID_maps) save[index] = tab for tab_save in plot_tabs: index, tab_save, dependencies = tab_save result_tab_idx = dependencies[0] result_tab = save[result_tab_idx] self.tab_widget.open_tab_by_save(tab_save, result_tab)
def select_file(): dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) filename, filter_type = dlg.getOpenFileNames() return filename
def getFilenamesFromUserSelection(path = '', extensions: str = None): filenames, _ = QFileDialog.getOpenFileNames(None, "Выбрать файлы", path, "Text Files (*.txt);;{0}".format(extensions if not extensions == None else ''), None) if (len(filenames) > 0): return filenames else: return None
def openMultiFile(): option=QFileDialog.Options() option|=QFileDialog.DontUseNativeDialog file=QFileDialog.getOpenFileNames(widget,"Select Multi File","default","All Files (*)",options=option) print(file[0])
def loadTransactions(self): self.file_paths, _ = QFileDialog.getOpenFileNames( self, "Choose transaction files", "/home", "JSON files (*.json)") self.data = TransActionLoader(self.file_paths).load_transactions()
def open_files(self): # очищаем колонки self.columns.clear() self.axe_y.clear() self.axe_y2.clear() self.axe_x.clear() self.field_x = [] self.field_y = [] self.field_y2 = [] self.files, _filter = QFileDialog.getOpenFileNames( self, 'Выбор данных: ', '', "GZ Files (*.gz) ;; CSV Files (*.csv) ;; txt (*.txt)") try: # Определение кодировки if self.filename_extension(): with open(self.files[0], 'rb') as f: raw_data = f.read(20000) self.encoding = chardet.detect(raw_data)['encoding'] # и разделителя csv with open(self.files[0], 'r', encoding=self.encoding) as f: print(f.readline(100)) if f.readline(100).count(';'): self.delimiter = ';' else: self.delimiter = '\t' # Считывание названия всех колонок self.name_column = pd.read_csv(self.files[0], encoding=self.encoding, delimiter=self.delimiter, nrows=0) # self.name_column.pop() # заполняем колонку ось columns (Выбирай параметр) for i, _ in enumerate(self.name_column): self.columns.insertItem(i, _) else: # Определение кодировки with gzip.open(self.files[0], 'rb') as f: raw_data = f.read(20000) self.encoding = chardet.detect(raw_data)['encoding'] # и разделителя gz with gzip.open(self.files[0], 'r') as f: if f.readline(100).decode(self.encoding).count(';'): self.delimiter = ';' else: self.delimiter = '\t' # Считывание названия всех колонок self.name_column = pd.read_csv(self.files[0], encoding=self.encoding, delimiter=self.delimiter, nrows=0) # заполняем колонку ось columns (Выбирай параметр) for i, _ in enumerate(self.name_column): self.columns.insertItem(i, _) except IndexError as e: print('не выбраны данные') # по умолчанию на ось columns (Выбирай параметр) добавляем 'time' # и тут же ее перемещяем на ось Х self.columns.addItem('time, c') self.columns.setCurrentRow(self.columns.count() - 1) self.axe_x.addItem(self.columns.takeItem(self.columns.currentRow())) self.columns.setCurrentRow(0) self.axe_x.setCurrentRow(0)
def browseFiles(self): names = QFileDialog.getOpenFileNames(self, 'Open files', '*.max') self.addFiles(names[0])
def upload_file(): files = QFileDialog.getOpenFileNames() print(files[0])
def openFileDialog(self): filename = QFileDialog.getOpenFileNames(self) if filename: self.filename = filename
from sys import executable, argv from subprocess import check_output from PyQt5.QtWidgets import QFileDialog, QApplication def gui_fnames(directory='./'): """Open a file dialog, starting in the given directory, and return the chosen filename""" # run this exact file in a separate process, and grab the result file = check_output([executable, __file__, directory]) return file.strip().decode("utf-8") if __name__ == "__main__": directory = argv[1] app = QApplication([directory]) fnames = QFileDialog.getOpenFileNames(None, "Select files for prediction...", directory, filter="All files (*)")[0] print(";".join(fnames))
def psbt_combiner(self, window, wallet): title = _("Select the PSBT file to load or PSBT files to combine") directory = '' fnames, __ = QFileDialog.getOpenFileNames(window, title, directory, "PSBT Files (*.psbt)") psbts = [] for fn in fnames: try: with open(fn, "rb") as f: raw = f.read() psbt = BasicPSBT() psbt.parse(raw, fn) psbts.append(psbt) except (AssertionError, ValueError, IOError, os.error) as reason: window.show_critical( _("Electrum-CHI was unable to open your PSBT file") + "\n" + str(reason), title=_("Unable to read file")) return warn = [] if not psbts: return # user picked nothing # Consistency checks and warnings. try: first = psbts[0] for p in psbts: fn = os.path.split(p.filename)[1] assert (p.txn == first.txn), \ "All must relate to the same unsigned transaction." for idx, inp in enumerate(p.inputs): if not inp.part_sigs: warn.append( fn + ':\n ' + _("No partial signatures found for input #%d") % idx) assert first.inputs[ idx].redeem_script == inp.redeem_script, "Mismatched redeem scripts" assert first.inputs[ idx].witness_script == inp.witness_script, "Mismatched witness" except AssertionError as exc: # Fatal errors stop here. window.show_critical( str(exc), title=_("Unable to combine PSBT files, check: ") + p.filename) return if warn: # Lots of potential warnings... window.show_warning('\n\n'.join(warn), title=_("PSBT warnings")) # Construct an Electrum transaction object from data in first PSBT file. try: tx = recover_tx_from_psbt(first, wallet) except BaseException as exc: if CC_DEBUG: from PyQt5.QtCore import pyqtRemoveInputHook pyqtRemoveInputHook() import pdb pdb.post_mortem() window.show_critical(str(exc), title=_("Unable to understand PSBT file")) return # Combine the signatures from all the PSBTS (may do nothing if unsigned PSBTs) for p in psbts: try: merge_sigs_from_psbt(tx, p) except BaseException as exc: if CC_DEBUG: from PyQt5.QtCore import pyqtRemoveInputHook pyqtRemoveInputHook() import pdb pdb.post_mortem() window.show_critical("Unable to merge signatures: " + str(exc), title=_("Unable to combine PSBT file: ") + p.filename) return # Display result, might not be complete yet, but hopefully it's ready to transmit! if len(psbts) == 1: desc = _("From PSBT file: ") + fn else: desc = _("Combined from %d PSBT files") % len(psbts) window.show_transaction(tx, desc)
def openfiles(self): fnames = QFileDialog.getOpenFileNames(self, '学点编程吧:打开多个文件', './') if fnames[0]: for fname in fnames[0]: with open(fname, 'r', encoding='gb18030', errors='ignore') as f: self.tx.append(f.read())
def getImagePath(self): imageDialog = QFileDialog(self, "选择多张图片") self.imagePathList, _ = imageDialog.getOpenFileNames() self.imageEdit.setText("选中%d个图片" % len(self.imagePathList))
def _add_torrents_triggered(self): paths, _ = QFileDialog.getOpenFileNames(self, 'Add torrents', self._control_thread.control.last_torrent_dir, 'Torrent file (*.torrent);;All files (*)') self.add_torrent_files(paths)
def open_file(self): fnamesRaw = QFileDialog.getOpenFileNames( self, 'Open File', 'C:\\Users\\ADiKo\\Desktop\\', 'txt file (*.txt)')[0] print(fnamesRaw) #self.csvFileName = fname.split('.')[0] + ".csv" results_dict = {"comp": 0, "cycle": 0, "x": [], "y": []} results_data = [] csv_results = [] csv_dict = {"comp": 0, "cycle": 0, "cs": 0, "hs": []} curComp = -1 curCycle = 0 lastCycleInFile = 0 fnames_dict = {} for f in fnamesRaw: k = f.split(".")[-2].split("_")[-1] fnames_dict[k] = f print(fnames_dict) l_dict = fnames_dict.keys() l_dict = list(l_dict) l_dict.sort() print(l_dict) try: for k in l_dict: fname = fnames_dict[k] f = open(fname, 'r') print("file opened: ", end="") print(fname) for line in f: if len(line) > 2: if line.startswith("Comp"): if curComp >= 0: results_data.append(results_dict) csv_results.append(csv_dict) results_dict = { "comp": 0, "cycle": 0, "x": [], "y": [] } csv_dict = { "comp": 0, "cycle": 0, "cs": 0, "hs": [] } curComp = int(line[7]) results_dict["comp"] = curComp csv_dict["comp"] = curComp elif line.startswith("Cyle"): l = line.split(" ") curCycle = int(l[2]) print("cur cycle is: %d" % (curCycle)) if curComp == 0: curCycle = int(curCycle / 2) + 1 else: curCycle = int(curCycle / 2) curCycle += lastCycleInFile results_dict["cycle"] = curCycle csv_dict["cycle"] = curCycle #lastCycleInFile = curCycle else: if line.startswith("cs") or line.startswith("hs"): l = line.split(",") results_dict["x"].append(int(l[1])) results_dict["y"].append(int(l[2])) else: l = line.split(",") results_dict["x"].append(int(l[1])) results_dict["y"].append(int(l[2])) if line.startswith("cs"): l = line.split(",") csv_dict["cs"] = int(l[4]) - int(l[1]) elif line.startswith("hs"): l = line.split(",") csv_dict["hs"].append(int(l[4]) - int(l[1])) results_data.append(results_dict) csv_results.append(csv_dict) f.close() lastCycleInFile = curCycle except Exception as ex: template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) print(message) for r in results_data: print(r) print() for r in csv_results: print(r) self.write_to_csv("Common Data.csv", csv_results) '''
def retranslateUi(self, ThirdOutput): _translate = QtCore.QCoreApplication.translate ThirdOutput.setWindowTitle(_translate("ThirdOutput", "MainWindow")) #Text in Title self.Third_Label.setText( _translate("ThirdOutput", "Classification Results for Selected Files")) #Text included in button self.backButton.setText( _translate("ThirdOutput", "Back to File Selection")) filename = QFileDialog.getOpenFileNames() # print(filename) path = filename[0] print(path) print(len(path)) ## if len(path) == 0: msg = QMessageBox() msg.setWindowTitle("Received Documents Info") msg.setText("Please insert at least 1 document") msg.setIcon(QMessageBox.Critical) x = msg.exec_() # this will show our messagebox elif len(path) > 0: msg = QMessageBox() msg.setWindowTitle("Received Documents Info") msg.setText("Correct Documents Input") #Below set path where tick.png is saved msg.setIconPixmap( QtGui.QPixmap( "G:/Nick/MSC Data Science/6th Semester/Capstone Project/Practice/New folder/tick.PNG" )) x = msg.exec_() # this will show our messagebox array2 = [] data2 = pd.DataFrame() counter = 0 for i in path: j = prepare(i) proba = model.predict_proba([j]) array2.append(proba[0]) ###### pdf = wi(filename=i, resolution=300) # fn replaced with i pdfimage = pdf.convert('tiff') pg = 1 for img in pdfimage.sequence: counter = counter + 1 pgn = str(pg) page = wi(image=img) page.save(filename=str(i + pgn) + '.tiff') # fn replaced with i pg += 1 print(">> done ", counter, ">>") ###### ###### root = os.listdir('G:/Capstone_Files/images') pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" images = [ cv2.imread(file, 0) for file in glob.glob('G:/Capstone_Files/images/*1.tiff') ] NoneType = type(None) ###### #Preprocces for any new inserted document in order to be prepared for text based classifier array = [] data = pd.DataFrame([]) total_info = [] count = 0 for i in images: image2 = preprocess(i) rotate = rotate_image(image2) if type(rotate) == NoneType: total_df = pytesseract.image_to_data(image2, lang='ell', output_type='data.frame') else: total_df = pytesseract.image_to_data(rotate, lang='ell', output_type='data.frame') total_df = total_df[total_df.conf > 59] total_df = total_df[total_df.text != ''] total_df = total_df[['text']] total_df['document'] = count total_df['lowercase'] = total_df['text'].str.lower() total_df[['our_corrected']] = total_df[['lowercase' ]].applymap(correction) total_df[['enchant_corrected' ]] = total_df[['lowercase']].applymap(enchant_correction) total_df['final_text'] = total_df.apply( lambda r: (r['our_corrected'] + r['enchant_corrected']) if r['our_corrected'] == "" else r['our_corrected'], axis=1) final_series = total_df.groupby('document')['final_text'].apply( list) final_df = pd.DataFrame(final_series) final_df['final_text_string'] = [ ' '.join(map(str, l)) for l in final_df['final_text'] ] doc_info = final_df['final_text_string'].tolist() total_info.extend(doc_info) doc_df_transformed = loaded_vectorizer.transform( [final_df['final_text_string']]) conf_table2 = loaded_model.predict_proba(doc_df_transformed) array.append(conf_table2[0]) data_final = data.append(pd.DataFrame(array), ignore_index=True) data_final = data_final.round(2) * 100 count = count + 1 # EXTRACTED WORDS FROM EVERY DOCUMENT a = [] for i in range(1, len(total_info) + 1): a.append(str(i)) b = ["Extracted Words from Document " + i for i in a] c = [i + ": " for i in b] total_info = [c[i] + total_info[i] for i in range(len(total_info))] self.listWidget = QListWidget() self.listWidget.addItems(total_info) self.listWidget.show() #=========================================================================================================== # BARPLOTS PRESENTING THE PROBABILITY FOR EVERY DOCUMENT FOR THE TWO MODELS data2 = data2.append(array2) data2.columns = [ "Purchase Receipt", "Service Receipt", "Police Report", "ΙΒΑΝ", "Contract", "Claim Statement" ] data2 = data2.rename(index=lambda x: x + 1) data2.index = data2.index.map(str) data2 = data2.rename(index=lambda x: "Document " + x) data2 = data2.round(2) * 100 fig, axarr = plt.subplots(2, 1, figsize=(22, 10), sharex=True) matplotlib.style.use('fivethirtyeight') data_final.plot.bar(ax=axarr[0], width=1.5) axarr[0].set_title("Text Based Classifier", fontsize=20, fontweight="bold", color="brown") axarr[0].get_legend().remove() data2.plot.bar(ax=axarr[1], width=1.5) axarr[1].set_title("Image Based Classifier", fontsize=20, fontweight="bold", color="brown") axarr[1].get_legend().remove() fig.legend( data2, # The line objects #labels=line_labels, # The labels for each line loc="center right", # Position of legend borderaxespad=2.2, # Small spacing around legend box facecolor="white", title="Legend", # Title for the legend title_fontsize=20, frameon=True, edgecolor="black") fig.text(0.04, 0.5, 'Probabilityy for each class', va='center', rotation='vertical', fontsize=20) plt.setp(plt.xticks()[1], rotation=0) plt.suptitle('Class Probability for each Document for both methods', fontsize=28, fontweight="bold") plt.subplots_adjust(right=0.85)
def openImage(self): folder_path = QFileDialog.getOpenFileNames() self.Imageloc.setText(str(folder_path[0][0]))
class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() self.create_elements() self.set_property() self.add_elements() self.clean_file_selection() self.add_connect() self.STOP = False def create_elements(self): self.mainLayout = QVBoxLayout() self.fileLayout = QHBoxLayout() self.fileLine = QLineEdit() self.fileButton = QPushButton('Open') self.unselectButton = QPushButton('Clean Selections') self.inverseButton = QPushButton('Inverse') self.fileDialog = QFileDialog(self) self.inverseThread = InverseThread(self) self.statusBar = QStatusBar(self) self.progressBar = QProgressBar() def set_property(self): # set main window properties self.setWindowTitle('Pdf Inverse') self.resize(600, 200) # set widget properties self.fileButton.setToolTip( 'Click here to open one or more pdf files ro inverse color') self.inverseButton.setToolTip('Click here to start inverse') self.fileLine.setReadOnly(True) self.statusBar.setSizeGripEnabled(False) def add_elements(self): self.setLayout(self.mainLayout) self.mainLayout.addLayout(self.fileLayout) self.fileLayout.addWidget(self.fileLine) self.fileLayout.addWidget(self.fileButton) self.fileLayout.addWidget(self.unselectButton) self.mainLayout.addWidget(self.inverseButton) self.mainLayout.addWidget(self.progressBar) def add_connect(self): self.fileButton.clicked.connect(self.open_file_dialog) self.unselectButton.clicked.connect(self.clean_file_selection) self.inverseButton.clicked.connect(self.inverse) @pyqtSlot() def open_file_dialog(self): self.pdf_path.extend( self.fileDialog.getOpenFileNames(self, 'Choose files to inverse', '.', '*.pdf')[0]) self.fileLine.setText(str(self.pdf_path)) self.inverseThread.set_pdf_path(self.pdf_path) @pyqtSlot() def clean_file_selection(self): self.pdf_path = [] self.fileLine.setText(str(self.pdf_path)) self.inverseThread.set_pdf_path(self.pdf_path) @pyqtSlot() def inverse(self): self.fileButton.setEnabled(False) self.unselectButton.setEnabled(False) self.inverseButton.setText('Processing...Click to stop') self.inverseButton.clicked.disconnect(self.inverse) self.inverseButton.clicked.connect(self.stop) self.inverseThread.start() @pyqtSlot() def stop(self): self.STOP = True self.inverseButton.clicked.disconnect(self.stop) self.inverseButton.clicked.connect(self.inverse) self.inverseButton.setEnabled(False) self.inverseButton.setText('Stopping...')
def open_pdf(self): fnames = QFileDialog.getOpenFileNames(self, '打开文件', './') # 注意这里返回值是元组 if fnames[0]: for fname in fnames[0]: self.lineEdit.setText(fname)
def load_file(mw, files=None): # mw = main window if files == None: files, filetype = QFileDialog.getOpenFileNames( mw, "選擇文件", mw.default_path, # 起始路径 "All Files (*);;Dicom Files (*.dcm);;Png Files (*.png);;JPEG Files (*.jpeg)" ) # 如果有讀到檔案 if len(files) == 0: return # 更新預設路徑 mw.default_path = os.path.split(files[0])[0] mw.json_para['path'] = mw.default_path mw.use_json('write') # 副檔名 mw.extension = os.path.splitext(files[0])[-1].lower() # 如果讀取到 Dicom 檔 if mw.extension == '.dcm': file = files[0] browse_path = file mw.default_path, mw.default_filename = os.path.split(file) mw.default_filename = mw.default_filename.split('.')[0] mw.filename = os.path.splitext(os.path.split(file)[-1])[0] mw.default_dirname = os.path.split(mw.default_path)[-1] dicom = pydicom.read_file(file) mw.IMGS = gui_tool.add_page(dicom.pixel_array) mw.img_preview = mw.IMGS[0] mw.num_of_img, mw.h, mw.w = mw.IMGS.shape[:3] filetype = '.dcm' mw.date, mw.time = '', '' # 讀取 dicom 的日期 if 'InstanceCreationDate' in dir(dicom): mw.date = dicom.InstanceCreationDate mw.date = datetime.date(int(mw.date[:4]), int(mw.date[4:6]), int(mw.date[6:])) elif 'StudyDate' in dir(dicom): mw.date = dicom.StudyDate mw.date = datetime.date(int(mw.date[:4]), int(mw.date[4:6]), int(mw.date[6:])) # 讀取 dicom 的時間 try: if 'InstanceCreationTime' in dir(dicom): mw.time = dicom.InstanceCreationTime mw.time = datetime.time(int(mw.time[:2]), int(mw.time[2:4]), int(mw.time[4:])) elif 'StudyTime' in dir(dicom): mw.time = dicom.StudyTime mw.time = datetime.time(int(mw.time[:2]), int(mw.time[2:4]), int(mw.time[4:])) except: mw.time = '' # 讀取 dicom 中 儀器廠商 if 'ManufacturerModelName' in dir(dicom) and 'Manufacturer' in dir( dicom): system_name = dicom.Manufacturer + ' - ' + dicom.ManufacturerModelName elif 'Manufacturer' in dir(dicom): system_name = dicom.Manufacturer elif 'ManufacturerModelName' in dir(dicom): system_name = dicom.ManufacturerModelName else: system_name = '' # 讀取 dicom 的 delta x, delta y if 'SequenceOfUltrasoundRegions' in dir(dicom): deltax = dicom.SequenceOfUltrasoundRegions[0].PhysicalDeltaX deltay = dicom.SequenceOfUltrasoundRegions[0].PhysicalDeltaY deltax = deltax // 0.000001 / 1000 deltay = deltay // 0.000001 / 1000 elif 'PixelSpacing' in dir(dicom): deltax, deltay = dicom.PixelSpacing deltax = deltax // 0.000001 / 1000 deltay = deltay // 0.000001 / 1000 else: deltax, deltay = mw.json_para['delta_x'], mw.json_para['delta_y'] # 讀取 dicom 的 fps if 'RecommendedDisplayFrameRate' in dir(dicom): mw.json_para['video_fps'] = dicom.RecommendedDisplayFrameRate else: pass # 如果讀到圖檔 elif mw.extension == '.png' or mw.extension == '.jpg' or mw.extension == '.jpeg' or mw.extension == '.mp4' or mw.extension == '.avi' or mw.extension == '.mov': browse_path = os.path.split(files[0])[0] mw.filename = os.path.split(browse_path)[-1] if mw.extension == '.mp4' or mw.extension == '.avi' or mw.extension == '.mov': mw.filename = os.path.splitext(os.path.split(files[0])[-1])[0] capture = cv2.VideoCapture(files[0]) ret, frame = capture.read() IMGS = [] while ret: IMGS.append(frame) ret, frame = capture.read() capture.release() mw.IMGS = np.asarray(IMGS) else: # 排序圖檔 files = np.asarray(files) temp = np.asarray( [int(file.split('.')[0].split('/')[-1]) for file in files]) temp = np.argsort(temp) files = files[temp] mw.IMGS = gui_tool.add_page( np.asarray([ cv2.imdecode(np.fromfile(file, dtype=np.uint8), -1) for file in files ])) if np.ndim(mw.IMGS) == 3: mw.IMGS = cv2.merge([mw.IMGS, mw.IMGS, mw.IMGS]) # 輸出影向預設的路徑與檔案名稱 mw.default_path = browse_path mw.default_filename = mw.filename mw.default_dirname = os.path.split(os.path.split(browse_path)[0])[-1] mw.img_preview = mw.IMGS[0] mw.num_of_img, mw.h, mw.w = mw.IMGS.shape[:3] filetype = '.' + files[0].split('.')[-1] mw.date, mw.time, system_name = '', '', '' deltax, deltay = mw.json_para['delta_x'], mw.json_para['delta_y'] # 如果讀入檔案不是 dicom 或是 圖檔 else: msg = QtWidgets.QMessageBox() msg.setWindowTitle('Warning') msg.setText('Please select the dicom or the image file.\n') msg.setIcon(QtWidgets.QMessageBox.Warning) msg.exec_() return print(mw.default_path) print(mw.default_filename) print(mw.default_dirname) # 寫入 檔案路徑 mw.textBrowser_browse.setText(browse_path) # 顯示超音波廠商、字體白色、根據字數調整 label size mw.label_manufacturer.setText(system_name) mw.label_manufacturer.setStyleSheet("color:white") mw.label_manufacturer.adjustSize() # 寫入 file detail 內容 mw.label_filetype_show.setText(filetype) mw.label_image_size_show.setText(str(mw.w) + ' x ' + str(mw.h)) mw.label_date_show.setText(str(mw.date)) mw.label_time_show.setText(str(mw.time)) mw.label_frame_show.setText(str(mw.num_of_img)) # 更新 josn 參數 mw.json_para['delta_x'] = deltax mw.json_para['delta_y'] = deltay mw.doubleSpinBox_delta_x.setValue(deltax) mw.doubleSpinBox_delta_y.setValue(deltay) # horizontalSlider_preview 設定最大值、歸零 mw.horizontalSlider_preview.setMaximum(len(mw.IMGS) - 1) mw.horizontalSlider_preview.setValue(0) # 預設的 template block 與 search window mw.spinBox_temp_size.setValue(mw.json_para['template_size']) mw.spinBox_temp_size.setRange(1, mw.h // 2) mw.spinBox_search_range.setValue(mw.json_para['search_size']) mw.spinBox_search_range.setRange(1, mw.h // 2) # 預設的 draw delay mw.default_draw_delay = mw.json_para['draw_delay'] mw.spinBox_drawing_delay.setValue(mw.default_draw_delay) mw.spinBox_drawing_delay.setRange(1, 100) # 建立預覽圖片、自適化調整 mw.show_preview_img(np.copy(mw.img_preview), mw.json_para['template_size'], mw.json_para['search_size']) # 預設上下限與初始頁數 mw.spinBox_start.setRange(0, mw.num_of_img - 1) mw.spinBox_end.setRange(0, mw.num_of_img - 1) mw.spinBox_start.setValue(0) mw.spinBox_end.setValue(mw.num_of_img - 1) #################### 額外控制功能的動作 #################### mw.spinBox_target_frame.setRange(0, mw.num_of_img - 1) # 清空 points mw.textBrowser_labeled_points.setText('') mw.textBrowser_auto_add_point.setText('') # Scaling 初始化 mw.scaling = 100 with open('saved_points.json', 'r') as f: saved_points = json.loads(f.read()) name = os.path.split(mw.json_para['path'])[-1] + '_' + str( mw.date) + '_' + mw.filename + mw.extension if name in saved_points.keys(): mw.textBrowser_auto_add_point.setText(saved_points[name])
def get_doc_dialog(self): self.file_li, a = QFileDialog.getOpenFileNames(self, 'Open file', "D:\\", "word(*.doc;*.docx;*.wps)") self.s.display_li.emit()
def actTbInputCsvClicked(self): dlg = QMessageBox.question(None, "操作提示", "您“确定”从XLS导入数据吗?", QMessageBox.Yes | QMessageBox.No) if (dlg == QMessageBox.Yes): file, ok1 = QFileDialog.getOpenFileNames(None, "请选择Xls文件打开", "", "Xls File (*.xls)") if (file.__len__() > 0): #self.twProductCategoryList.clear() #self.twProductCategoryList.setRowCount(0) #self.twProductCategoryList.setHorizontalHeaderLabels(['ID', 'Title', 'Code', 'Updated At', 'Created At', 'Level', 'Parent Id', ]) # 读取文件总行数 try: nowTime = datetime.datetime.now() #tempfile = open(file, "r") #打开XLS文件 data = xlrd.open_workbook(file[0]) #获取XLS文件里的第二个表格 table = data.sheet_by_index(1) importLines = table.nrows - 1 #self.twProductCategoryList.setRowCount(importLines or 2) self.mainWin.progressBarShow(importLines) self.mainWin.statusMsg('处理数据中...') #检查数据库与上传文件内容配对 '''优化导入检查''' differenceRecords = {} categories = Amazon_Product_Category.select( Amazon_Product_Category.title, Amazon_Product_Category.code).order_by( Amazon_Product_Category.code.desc()).execute() rowCount = self.twProductCategoryList.rowCount() stratTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("开始时间:" + stratTime) for i in range(importLines): title_list = table.row_values(i)[1].split('/') if (i > 0): for index in range(rowCount): # print(self.twProductCategoryList.item(i, 1).text()) if str( self.twProductCategoryList.item( index, 2).text() ) == str(table.row_values(i)[0]) and str( title_list[-1] ) != self.twProductCategoryList.item(index, 2).text(): differenceRecords[ self.twProductCategoryList.item( index, 2 )] = self.twProductCategoryList.item( index, 2) endTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print("结束时间:" + endTime) self.mainWin.statusMsg('开始导入 {0}...'.format( nowTime.strftime('%H:%M:%S'))) msg = ",".join(str(i) for i in differenceRecords.keys()) if (len(differenceRecords) > 0): dlg = QMessageBox.question( None, "操作提示", 'Node ID为' + msg + '的已修改,您“确定”要更新修改记录吗', QMessageBox.Yes | QMessageBox.No) if (dlg == QMessageBox.Yes): skipRecords = {} else: skipRecords = differenceRecords else: skipRecords = {} for i in range(importLines): if (i > 0): self.actTbSve(table.row_values(i), i, skipRecords) #csvFile.close() self.mainWin.progressBarContinue() endTime = datetime.datetime.now() self.mainWin.statusMsg('完成导入 {0}条数据,用时{1}'.format( importLines, (endTime - nowTime))) self.mainWin.progressBarHide() self.actTbRefreshClicked() except Exception as e: import traceback traceback.print_exc() logger.info(e) pass
def _selectFiles(self): # Find the directory of the most recently opened image file mostRecentStackDirectory = preferences.get("DataSelection", "recent stack directory") if mostRecentStackDirectory is not None: defaultDirectory = os.path.split(mostRecentStackDirectory)[0] else: defaultDirectory = os.path.expanduser("~") options = QFileDialog.Options(QFileDialog.ShowDirsOnly) if ilastik.config.cfg.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog h5exts = [x.lstrip(".") for x in OpStreamingH5N5SequenceReaderM.H5EXTS] # Launch the "Open File" dialog extensions = vigra.impex.listExtensions().split() extensions.extend(h5exts) extensions.extend(OpInputDataReader.n5Selection) filt = "Image files (" + " ".join("*." + x for x in extensions) + ")" options = QFileDialog.Options() if ilastik.config.cfg.getboolean("ilastik", "debug"): options |= QFileDialog.DontUseNativeDialog fileNames, _filter = QFileDialog.getOpenFileNames( self, "Select Images for Stack", defaultDirectory, filt, options=options) # For the n5 extension, the attributes.json file has to be selected in the file dialog. # However we need just the n5 directory-file. for i in range(len(fileNames)): if os.path.join("n5", "attributes.json") in fileNames[i]: fileNames[i] = fileNames[i].replace( os.path.sep + "attributes.json", "") msg = "" if len(fileNames) == 0: return pathComponents = PathComponents(fileNames[0]) if ((len(fileNames) == 1) and pathComponents.extension not in OpStreamingH5N5SequenceReaderM.H5EXTS + OpStreamingH5N5SequenceReaderM.N5EXTS): msg += "Cannot create stack: You only chose a single file. " msg += "If your stack is contained in a single file (e.g. a multi-page tiff) " msg += 'please use the "Add File" button.' QMessageBox.warning(self, "Invalid selection", msg) return None directory = pathComponents.externalPath preferences.set("DataSelection", "recent stack directory", directory) if (pathComponents.extension in OpStreamingH5N5SequenceReaderM.H5EXTS or pathComponents.extension in OpStreamingH5N5SequenceReaderM.N5EXTS): if len(fileNames) == 1: # open the dialog for globbing: file_name = fileNames[0] dlg = H5N5StackingDlg( parent=self, list_of_paths=self._findInternalStacks(file_name)) if dlg.exec_() == QDialog.Accepted: globstring = "{}/{}".format(file_name, dlg.get_globstring()) self.patternEdit.setText(globstring) self._applyPattern() return None else: return None else: # check for internal paths internal_paths = self._h5N5FindCommonInternal(fileNames) if len(internal_paths) == 0: msg += "Could not find a unique common internal path in" msg += directory + "\n" QMessageBox.warning(self, "Invalid selection", msg) return None elif len(internal_paths) == 1: fileNames = [ "{}/{}".format(fn, internal_paths[0]) for fn in fileNames ] else: # Ask the user which dataset to choose dlg = SubvolumeSelectionDlg(internal_paths, self) if dlg.exec_() == QDialog.Accepted: selected_index = dlg.combo.currentIndex() selected_dataset = str(internal_paths[selected_index]) fileNames = [ "{}/{}".format(fn, selected_dataset) for fn in fileNames ] else: msg = "No valid internal path selected." QMessageBox.warning(self, "Invalid selection", msg) return None self._updateFileList(fileNames)
def actTbInputSkuAndCategoryClicked(self): dlg = QMessageBox.question(None, "操作提示", "您“确定”从CSV导入数据吗?", QMessageBox.Yes | QMessageBox.No) if (dlg == QMessageBox.Yes): file, ok1 = QFileDialog.getOpenFileNames(None, "请选择XLS文件打开", "", "Xls File (*.xls)") if (file.__len__() > 0): try: # 打开XLS文件 data = xlrd.open_workbook(file[0]) # 获取XLS文件里的第二个表格 table = data.sheet_by_index(0) importLines = table.nrows - 1 for i in range(importLines): if (i > 0): #根据NodeID查询对应分类表ID nodeId = int(table.row_values(i)[1]) sku = table.row_values(i)[0] print(sku) try: categoryRow = Amazon_Product_Category.select( ).where(Amazon_Product_Category.code == nodeId).get() categoryId = categoryRow.id except Amazon_Product_Category.DoesNotExist: categoryId = 0 try: skuRow = Na_Product_Asin.select().where( Na_Product_Asin.sku == sku).get() skuId = skuRow.id except Na_Product_Asin.DoesNotExist: skuId = 0 print(categoryId) print(skuId) #return try: if int(categoryId) > 0 and int(skuId) > 0: #掺入到NA PRODUCT ASIN CATEGORYB表中 Na_Product_Asin_Amazon_Category.insert( productasinmodel_id=skuId, productcategorymodel_id=categoryId, ).on_conflict( conflict_target=( Na_Product_Asin_Amazon_Category.id, ), preserve=( Na_Product_Asin_Amazon_Category.id ), update={ 'productasinmodel_id': skuId, 'productcategorymodel_id': categoryId }).execute() except Exception as e: import traceback traceback.print_exc() logger.info(e) except Exception as e: import traceback traceback.print_exc() logger.info(e) pass
def on_choose_files_clicked(self, checked): filenames, _ = QFileDialog.getOpenFileNames(self.window(), tr("Please select the files"), QDir.homePath()) for filename in filenames: self.dialog_widget.create_torrent_files_list.addItem(filename)
def openfiles2(self): fnames = QFileDialog.getOpenFileNames(self, '打开第二个文件', './') # 注意这里返回值是元组 if fnames[0]: for fname in fnames[0]: self.tx2.append(fname)
def choseFileAction(self): options = QFileDialog.Options() #options |= QFileDialog.DontUseNativeDialog files, _ = QFileDialog.getOpenFileNames(self,"Select files") if files: self.imagesList.addFilesToList(files)
def on_add_torrent_browse_file(self): filenames = QFileDialog.getOpenFileNames(self, "Please select the .torrent file", "", "Torrent files (*.torrent)") if len(filenames[0]) > 0: [self.pending_uri_requests.append(u"file:%s" % filename) for filename in filenames[0]] self.process_uri_request()