def file_dialog(dir='', for_open=True, fmt='', is_folder=False): """Dialog z eksploratorem Windows. Otwieranie/tworzenie folderów i plików.""" options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog options |= QFileDialog.DontUseCustomDirectoryIcons dialog = QFileDialog() dialog.setOptions(options) dialog.setFilter(dialog.filter() | QDir.Hidden) if is_folder: # Otwieranie folderu dialog.setFileMode(QFileDialog.DirectoryOnly) else: # Otwieranie pliku dialog.setFileMode(QFileDialog.AnyFile) # Otwieranie / zapisywanie: dialog.setAcceptMode( QFileDialog.AcceptOpen) if for_open else dialog.setAcceptMode( QFileDialog.AcceptSave) # Ustawienie filtrowania rozszerzeń plików: if fmt != '' and not is_folder: dialog.setDefaultSuffix(fmt) dialog.setNameFilters([f'{fmt} (*.{fmt})']) # Ścieżka startowa: if dir != '': dialog.setDirectory(str(dir)) else: dialog.setDirectory(str(os.environ["HOMEPATH"])) # Przekazanie ścieżki folderu/pliku: if dialog.exec_() == QDialog.Accepted: path = dialog.selectedFiles()[0] return path else: return ''
def on_pushButton_clicked(self): curPath = QDir.currentPath() # 获取系统当前目录 dlgTitle = "选择一个文件" # 对话框标题 filt = "文本文件(*.txt);;" # 文件过滤器 # filename = QFileDialog.getOpenFileName(self, dlgTitle, curPath, filt) #self.ui.plainTextEdit.appendPlainText(filename) #self.ui.plainTextEdit.appendPlainText("\n" + filtUsed) filenam = QFileDialog() filenam.setFileMode(QFileDialog.AnyFile) #设置过滤器 filenam.setFilter(QDir.Files) if filenam.exec_(): filenames = filenam.selectedFiles() f = pd.read_csv(filenames[0], sep='\s+') # with f: # data = f.read() # #self.contents.setText(data) # print(data) self.data = f print(self.data)
def load_excel_data(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setFilter(QDir.Files) if dialog.exec_(): filename = dialog.selectedFiles() if filename[0].endswith('.xlsx'): df = pd.read_excel(filename[0]) if df.size == 0: return else: df.fillna('', inplace=True) self.table.setRowCount(df.shape[0]) self.table.setColumnCount(df.shape[1]) # returns pandas array object for row in df.iterrows(): values = row[1] for col_index, value in enumerate(values): if isinstance(value, (float, int)): value = '{0:0,.0f}'.format(value) tableitem = QTableWidgetItem(str(value)) self.table.setItem(row[0], col_index, tableitem) self.table.setColumnWidth(2, 300) else: pass
def FileDialog(directory='', forOpen=True, fmt='', isFolder=False): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog options |= QFileDialog.DontUseCustomDirectoryIcons dialog = QFileDialog() dialog.setOptions(options) dialog.setFilter(dialog.filter() | QtCore.QDir.Hidden) # ARE WE TALKING ABOUT FILES OR FOLDERS if isFolder: dialog.setFileMode(QFileDialog.DirectoryOnly) else: dialog.setFileMode(QFileDialog.AnyFile) # OPENING OR SAVING dialog.setAcceptMode(QFileDialog.AcceptOpen) if forOpen else dialog.setAcceptMode(QFileDialog.AcceptSave) # SET FORMAT, IF SPECIFIED if fmt != '' and isFolder is False: dialog.setDefaultSuffix(fmt) dialog.setNameFilters([f'{fmt} (*.{fmt})']) # SET THE STARTING DIRECTORY if directory != '': dialog.setDirectory(str(directory)) else: dialog.setDirectory(str(ROOT_DIR)) if dialog.exec_() == QDialog.Accepted: path = dialog.selectedFiles()[0] # returns a list return path else: return ''
def load_file(self, machineCode): self.clear() dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFile) dialog.setFilter(QDir.Files) if dialog.exec_(): fileName = dialog.selectedFiles() if fileName[0].endswith('.json'): with open(fileName[0], 'r') as f: data = json.load(f) self.handle_json(data) elif fileName[0].endswith('.txt') or fileName[0].endswith('.asm'): with open(fileName[0], 'r') as f: if not machineCode: asm = [line.rstrip('\n') for line in f] else: asm = [line for line in f] if (asm[0][0] != "0" and asm[0][0] != "1") and machineCode: show_popup(True, True) f.close() else: self.tableWidget.setRowCount(0) self.fetch_and_decode(asm, machineCode) isa.PC = -4 f.close() else: show_popup(True, False)
def file_dlg(self, text): msg_box = QMessageBox() msg_box.setIcon(QMessageBox.Question) try: msg_box.setWindowIcon( QtGui.QIcon(os.path.join("misc", "archerrank2.svg"))) except FileNotFoundError: msg_box.setWindowIcon( QtGui.QIcon( os.path.abspath( os.path.join(os.path.dirname(sys.argv[0]), "misc", "archerrank2.svg")))) msg_box.setText(self.tr("Question")) msg_box.setInformativeText(text) msg_box.addButton(self.tr('Load'), QMessageBox.AcceptRole) msg_box.addButton(self.tr('New'), QMessageBox.AcceptRole) msg_box.addButton(self.tr('Exit'), QMessageBox.NoRole) reply = msg_box.exec_() if reply == 0: fileName, _ = QFileDialog.getOpenFileName( None, "QFileDialog.getOpenFileName()", "", "Acherrang2 Files (*.sqlite)") return fileName elif reply == 1: filedialog = QFileDialog(msg_box) filedialog.setFilter(filedialog.filter() | QtCore.QDir.Hidden) filedialog.setDefaultSuffix('sqlite') filedialog.setAcceptMode(QFileDialog.AcceptSave) filedialog.setNameFilters(["Acherrang2 Files (*.sqlite)"]) if filedialog.exec_() == QFileDialog.Accepted: return filedialog.selectedFiles()[0] return else: return "exit"
def select_files(self): '''选择文件''' try: box = QtWidgets.QMessageBox() if self.Oline == 1: box.warning(self, '警告', '文件上传中,请稍后重试!') else: self.progressBar.setValue(0) self.textBrowser_2.clear() # self.Oline = 1 #代表文件端口已连接 dif = QFileDialog() dif.setFileMode(QFileDialog.AnyFile) #设置打开任意文件 dif.setFilter(QDir.Files) #文件过滤 if dif.exec_(): # 接受选中文件的路径,默认为列表 file_path = dif.selectedFiles() #获得文件绝对路径 # file_name = os.path.basename(file_path[0]) #获得文件名 self.textBrowser.setText(file_path[0]) self.textBrowser_2.append('文件名:' + file_path[0]) file_size = os.path.getsize(file_path[0]) # 获取文件大小 new_file_size = round(file_size / 1024 / 1024, 2) new_file_size = '文件大小:' + str(new_file_size) + 'MB' self.textBrowser_2.append(new_file_size) file_md5 = self.file_md5(file_path[0]) self.textBrowser_2.append('文件md5为:' + file_md5) except Exception as f: print(f)
def file_chooser(self): dialog = QFileDialog() dialog.setFilter(dialog.filter() | QtCore.QDir.Hidden) dialog.setDefaultSuffix("mp4") dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setNameFilters(["H.264 (*.mp4)", "MKV (*.mkv)"]) if dialog.exec_() == QDialog.Accepted: self.a6c1.setText(dialog.selectedFiles()[0])
def open_model(self): dig = QFileDialog() dig.setFileMode(QFileDialog.AnyFile) dig.setFilter(QDir.Files) dig.exec_() file_path = dig.selectedFiles()[0] print(file_path) return file_path
def set_path(self): dlg = QFileDialog(self, self.tr("Choose Path"), os.path.expanduser("~/")) dlg.setFileMode(self.type_of_file) if self.filter: dlg.setFilter([self.filter]) if dlg.exec_(): names = dlg.selectedFiles() self.text_edit.setText(names[0])
def getText2(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) #可选任意文件 dialog.setFilter(QDir.Files) if dialog.exec_(): #该方法用于选择文件,如果选中文件则返回true filenames = dialog.selectedFiles() #获取选中文件名列表 print(filenames) self.txtDestionPath.setPlainText(filenames[0])
def getfile(self): q_file = QFileDialog() q_file.setFileMode(QFileDialog.AnyFile) q_file.setFilter(QDir.Files) if q_file.exec(): filenames = q_file.selectedFiles() print(filenames[0]) s = filenames[0] sendfile(s)
def action_select_output_files_path(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog options |= QFileDialog.DontUseCustomDirectoryIcons dialog = QFileDialog() dialog.setOptions(options) dialog.setFilter(dialog.filter() | QDir.Hidden) path = dialog.getExistingDirectory(self, 'Select directory', options=options) if path: self.lineedit_output_files_path.setText(path)
def load_text(self): file_dialog = QFileDialog() file_dialog.setFileMode(QFileDialog.AnyFile) file_dialog.setFilter(QDir.Files) if file_dialog.exec(): file = file_dialog.selectedFiles() with open(file[0], 'r', encoding='utf-8') as f: # 加encoding是为了防止加载中文内容时出错 self.contents.setText(f.read()) pass
def open_directory(): dialog = QFileDialog() dialog.setFileMode(QFileDialog.Directory) dialog.setFilter(QDir.Dirs | QDir.NoDotAndDotDot) dialog.setWindowTitle('从指定文件夹复制样本:') name = None if dialog.exec(): name = dialog.selectedFiles()[0] logger.debug("name is %s, length %s", name, len(name)) return name
def load_text(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setFilter(QDir.Files) if dialog.exec_(): filenames = dialog.selectedFiles() with open(filenames[0], encoding='utf-8', mode='r') as f: data = f.read() self.contents.setText(data)
def getfiles(self): dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter(QDir.Files) if dlg.exec_(): filenames = dlg.selectedFiles() f = open(filenames[0], 'r') with f: data = f.read() self.contents.setText(data)
def open_file(self): dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter(QDir.Files) if dlg.exec_(): filename = dlg.selectedFiles() with open(filename[0], 'r') as f: data = f.read() self.textEdit.setText(data)
def load_file(self): print("加载文件") dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter(QDir.Files) if dlg.exec_(): filenames = dlg.selectedFiles() print(filenames[0]) self.read_bin(filenames[0])
def loadtxt(self): dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter(QDir.Files) global data #定义全局变量data,后面的各种压缩算法需要使用 if dlg.exec_(): filenames = dlg.selectedFiles() f = open(filenames[0], 'r') with f: data = f.read() self.textEdit.setText(data)
def selectfile(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setFilter(QDir.Files) if dialog.exec_(): filenames= dialog.selectedFiles() f= open(filenames[0],encoding='utf-8') with f: data = f.read() self.textEdit.setText(data)
def selectconfig(self): try: file = QFileDialog() file.setFileMode(QFileDialog.AnyFile) file.setFilter(QDir.Files) if file.exec_(): filename = file.selectedFiles() PATHDATA['config'] = filename[0] self.configLable.setText(filename[0]) except IOError: logger.exception("选择数据不符规则数据无效")
def getText(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) #可选任意文件 dialog.setFilter(QDir.Files) if dialog.exec_(): #该方法用于选择文件,如果选中文件则返回true filenames = dialog.selectedFiles() #获取选中文件名列表 print(filenames) f = open(filenames[0], 'r') with f: data = f.read() self.contents.setText(data)
def getText(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) #可选任意文件 dialog.setFilter(QDir.Files) if dialog.exec_(): #该方法用于选择文件,如果选中文件则返回true filenames = dialog.selectedFiles() #获取选中文件名列表 print(filenames) f = open(filenames[0], 'r') with f: self.txtSourcePath.setPlainText(filenames[0]) print(filenames)
def save(self): try: dif = QFileDialog() dif.setFileMode(QFileDialog.Directory) # 设置打开任意文件夹 dif.setFilter(QDir.Files) # 文件过滤 if dif.exec_(): # 接受选中文件的路径,默认为列表 dir_path = dif.selectedFiles() # 获得文件夹绝对路径 # file_name = os.path.basename(file_path[0]) #获得文件名 self.textBrowser.setText(dir_path[0]) except Exception as f: print(f)
def get_text_file(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setFilter(QDir.Files) if dialog.exec_(): file_name = dialog.selectedFiles() with open(file_name[0], 'r', encoding='utf-8') as f: data = f.read() self.editor.setPlainText(data) f.close()
def add_folder(self): try: self.__logger.info("add action sample folder") dlg = QFileDialog() dlg.setFileMode(QFileDialog.Directory) dlg.setFilter(QDir.Dirs | QDir.NoDotAndDotDot) if dlg.exec(): # get folder name folder_name = dlg.selectedFiles()[0] self.__logger.debug("open file name %s", folder_name) if folder_name == "": return if False in [ os.path.isdir(folder_name), os.path.isdir(self.__usr_label_path) ]: self.__logger.error("%s or %s is not directory", folder_name, self.__usr_label_path) return # if image in folder, normalize it # NormFolderImage(folderName) # build new and remove dst path _, name = os.path.split(folder_name) if self._check_valid(name): dst_path = os.path.join(self.__usr_label_path, name) if os.path.exists(dst_path): self.__logger.info("remove tree %s", dst_path) shutil.rmtree(dst_path) # copy folder shutil.copytree(folder_name, dst_path) item = self.__ui.tree_widget_left.currentItem() child = QTreeWidgetItem() child.setText(0, name) child.setText(2, ITEM_TYPE_IMAGE_FLODER) child.setText(3, dst_path) icon = QIcon() icon.addPixmap(QPixmap(":/menu/file.png"), QIcon.Normal, QIcon.Off) child.setIcon(0, icon) get_file_list(dst_path, child, 1) item.addChild(child) else: show_warning_tips("文件夹{}已存在,请检查".format(name)) dlg.popUp() except RuntimeError as error: self.__logger.info("change image failed, error %s", error)
def SelectFile(self): filedialog = QFileDialog() filedialog.setFileMode(QFileDialog.AnyFile) filedialog.setFilter(QDir.Files) if filedialog.exec(): filenames = filedialog.selectedFiles() print(filenames[0]) with open(filenames[0], encoding='utf-8', mode='r') as file: print(file) data = file.read() print(data) self.texts.setText(data)
def get_file(contents): dialog = QFileDialog() dialog.setFileMode(QFileDialog.AnyFile) dialog.setFilter(QDir.Files) # 维持窗口 if dialog.exec(): # 返回的是列表 file_names = dialog.selectedFiles() # print(file_names) with open(file_names[0], 'r', encoding='utf-8') as fi: data = fi.read() contents.setText(data)
def getfiles(self): dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter("Text files (*.txt)") filenames = [] #QStringList() if dlg.exec_(): filenames = dlg.selectedFiles() f = open(filenames[0], 'r') with f: data = f.read() self.contents.setText(data)