def openFolderDialog(self, buttonName): global sourceDir, destinationDir, ipAddress, user root = tk.Tk() root.withdraw() rootFolder = repr(os.getcwd()) rootFolder = rootFolder.replace("\\\\", "\\").replace("'", '') rootFolder += '\Folder_Structure' if (buttonName == 'source'): temp = sourceDir sourceDir = tkfd.askdirectory(parent=root,initialdir="/",title='Please select the source directory') if (sourceDir == ''): sourceDir = temp elif (buttonName == 'destination'): temp = destinationDir destinationDir = 'a' # Download the folder structure from the server #try: cmd = 'rsync -a -v -z -ssh --delete --delete-excluded ' + '-f"+ */" -f"- *" ' + user + '@' + ipAddress + ':Data/ ' + sync.convertPathToCygdrive(rootFolder) print (cmd) #TODO insert proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) remainder = str(proc.communicate()[0]) ibis = remainder.replace('\\n', '\n') #print(remainder) print(ibis) # output = '' # while not 'password' in output: # output = proc.stdout.readline() # print(output) # proc.stdin.write('ibiscp') #except: # self.showMessage(3, QtGui.QSystemTrayIcon.Warning, 'Folder structure could not update!') while (not rootFolder in destinationDir) and (destinationDir != ''): destinationDir = tkfd.askdirectory(parent=root,initialdir=rootFolder,title='Please select the destination directory inside the folder: ' + rootFolder) destinationDir = destinationDir.replace("/", "\\") if (destinationDir == ''): destinationDir = temp # Change the folder path to server path destinationDir = 'Server/' + destinationDir[(len(rootFolder)+1):] self.setText() self.enableAddButton()
def add_folder_pair(self): folder1 = filedialog.askdirectory() folder2 = filedialog.askdirectory() self.listbox1.insert(END ,folder1) self.listbox2.insert(END, folder2) self.root.update() self.folders.append([folder1, folder2])
def proceso(): ent = filedialog.askdirectory() # directorio entrada ini = int(inicio.get()) pas = int(paso.get()) fin = int(final.get()) guar = nombre.get() sali = filedialog.askdirectory() #directorio salida rango = range(ini,fin + pas,pas) arc = open(str(sali)+"/"+str(guar),"w") for i in rango: data = open(str(ent)+"/defo."+str(i),"r") linea = data.readlines() con = 0 for j, line in enumerate(linea): if j > 9: spl = line.split() if float(spl[6]) < 3.5: con = con + 1 else: continue arc.write(str(i)+" ") arc.write(str(con)) arc.write("\n") data.close() arc.close()
def proceso(): v = filedialog.askdirectory() ini = inicio.get() pa = paso.get() fi = final.get() nom = nombre.get() o = filedialog.askdirectory() cmd = "ovitos strucs_argv.py %s %s %s %s %s %s"%(ini,pa,fi,nom,v,o) os.system(cmd)
def loadFramesByDirectory(self): if self.debug_FLAG: if self.db == 'salsa': self.dname = "Data\\Salsa\\Videos\\" + self.debug_fastaccess + "_kinect_1" elif self.db == 'calus': self.dname = "Data\\Calus\\frames" else: if self.db == 'salsa': self.dname = askdirectory(initialdir='Data\\Salsa\\Videos') elif self.db == 'calus': self.dname = askdirectory(initialdir='Data\\Calus') if self.dname: try: self.entry_name_frames.insert(0,"..." + self.dname[-30:]) self.indexFrames = [] for file in os.listdir(self.dname): dum, self.checkvideof_ext = os.path.splitext(file) if self.checkvideof_ext in ('.jpeg', '.JPG', '.JPEG', '.png', '.bmp', '.PNG', '.BMP'): dum, self.videof_ext = os.path.splitext(file) k = file.rfind("_") l = file.rfind(".") iFrame = file[k+1:l] if iFrame[0] == 'f': iFrame = iFrame[1:] self.indexFrames.append(int(iFrame)) self.prefixname = file[:k+2] else: self.indexFrames.append(int(iFrame)) self.prefixname = file[:k+1] self.indexFrames = sorted(self.indexFrames) self.videoStatusSTR.set( str(len(self.indexFrames)) + " Frames" ) self.videoLoadedFlag = True elif file in ('Thumbs.db'): continue else: showerror("Fail", "Only jpeg, jpg, JPG, bmp, BMP, png, PNG frames are supported") self.videoLoadedFlag = False return self.checkContinueEnable() except Exception as e: # <- naked except is a bad idea self.videoLoadedFlag = False self.checkContinueEnable() showerror("Error", ("Open Source File\n'%s'" % e) + "\n" + ("Failed to open directory\n'%s'" % self.dname)) return return
def askdirectory(): """Returns a selected directoryname.""" newPath = tkFileDialog.askdirectory(**dir_opt) if(newPath != ""): savePath.set(newPath) else: print("Hick")
def encrypt_dir(self): source_path = tkFileDialog.askdirectory() print(source_path) self.get_entry() excrypt.AES_dir_encrypt(source_path, self.key) print("Encrypted dir")
def main(): # for testing with just one file # fileName =filedialog.askopenfilename( # title = "Media file to query:", # initialdir = "C:/Users/grant/Documents/scratch/sonySDStructure" # ) # # # if fileName != "" : # print('\n'+fileName + ' becomes ' + getEXIFTime(fileName)) #close the root window root = tk.Tk() root.withdraw() stillsPath = filedialog.askdirectory( title = "Directory in which to rename jpg & ARW & CR2 & Tif files ", initialdir = "C:/Users/grant/Documents/scratch/sonySDStructure/DCIM/10060708" ) print(stillsPath) # Exit on cancel! if stillsPath == "" : return start_time=time.time() #renameStillsFolder(stillsPath) newNames = createSequencedNames(stillsPath) renameStillsFolder(stillsPath,newNames) # Double check what happens to sequence numbers on renaming renamed files. Seems to be dependent on natural order? # maybe sort by EXIF date if seq is the same for the whole folder (since it defaults to year in this case) print ('Done. Execution took {:0.3f} seconds'.format((time.time() - start_time)))
def folder_dlg(self): foldername = filedialog.askdirectory() if foldername: foldername = self._fix_paths_on_windows(foldername) self.foldername = foldername self.most_recent = 'folder' self.update_label()
def dir_open(self): root = self; dirname = askdirectory(); self.CopyFromText.delete(1.0,END); self.CopyToText.delete(1.0,END); self.CopyFromText.insert(END,dirname); self.CopyToText.insert(END,dirname);
def gui_inputs(): """create gui interface and return the required inputs Returns ------- infile : str pathname to the shapefile to apply the split field : str name of the field in the shape file dest : str folder name to save the outputs """ # locate your input shapefile print("select your input file") root = Tk() infile = tkfd.askopenfilename(title = "Select your shapefile", initialdir = "C:/", filetypes = (("shapefile", "*.shp"), ("all files", "*.*"))) # define destination -folder- where output -shapefiles- will be written print("select your output dir") dest = tkfd.askdirectory(title = "Select your output folder", initialdir = "C:/") root.destroy() # choose field to split by attributes print("Select your field name") field_options = _extract_attribute_field_names(infile) field = create_field_form(field_options) print("selection done") return infile, field, dest
def askroot(self): dir=filedialog.askdirectory(title="Select Comcraft Source Directory",mustexist=True, initialdir=self.ccdir) if dir and os.path.exists(os.path.join(dir,"net\\comcraft\\src")): self.config.merge('settings',{'comcraft_root':dir.replace('/','\\')}) else: if messagebox.askokcancel("Not found","Could not locate source, reselect folder?"): self.askroot()
def _handle_hashdb_directory_chooser(self, *args): hashdb_directory = fd.askdirectory( title="Open hashdb Database Directory", mustexist=True) if hashdb_directory: self._hashdb_directory_entry.delete(0, tkinter.END) self._hashdb_directory_entry.insert(0, hashdb_directory)
def confirm_name(info_lines, line_num, filetypes, title): """GUI asks user to choose a file/directory if the existing cannot be found""" # set initial variables, if filetypes is blank, then a directory is wanted path = info_lines[line_num - 1].rstrip('\r\n') directory = filetypes is None # if the path does not exist, prompt for a new one if not os.path.exists(path): if DEBUG: print("path " + str(path) + " does not exist") Tk().withdraw() if directory: path = askdirectory(title = title) else: path = askopenfilename(filetypes = filetypes, title = title) # throw SystemExit exception if the user does not choose a valid path if not os.path.exists(path): sys.exit() # save the new path to the array if the user chooses a valid path else: if DEBUG: print(str(info_lines[line_num - 1]).rstrip('\r\n') + " will be changed to " + str(path)) info_lines[line_num - 1] = path + "\n" elif DEBUG: print(str(path) + " exists") return path
def askDirectory(self): optionsd = {} optionsd['initialdir'] = 'C:\\' optionsd['mustexist'] = False optionsd['parent'] = self.root optionsd['title'] = 'This is a title' return self.loadAll(filedialog.askdirectory(**optionsd))
def getFile(self): fn = askdirectory() self.fileName.configure(state='normal') self.fileName.delete(0, tk.END) self.fileName.insert(0, fn) self.fileName.configure(state='disabled') self.directory = fn
def gogo(entries): # name = (entries['Session Name'].get()) epsilon = (int(entries['Epsilon'].get())) min_neighbors = (int(entries['Minimum Neighbors'].get())) mini_epsilon = (int(entries['Mini Epsilon'].get())) mini_min_neighbors = (int(entries['Mini Minimum Neighbors'].get())) prot_mode = 2 if entries['Mode'].get() == "2 protein" else 1 d_type = (entries['Data Type'].get()) path = filedialog.askdirectory() f_color = (entries['color'].get()) f_points = (entries['#points'].get()) f_red_points = (entries['#red points'].get()) f_green_points = (entries['#green points'].get()) f_density = (entries['density'].get()) f_coloc = (entries['colocalized'].get()) f_x_angle = (entries['angle x'].get()) f_y_angle = (entries['angle y'].get()) f_size = (entries['size'].get()) print(path) messagebox.showinfo("Work in progress", "Please wait till' it's done... You'll get a message (for now just click OK).") go(epsilon, min_neighbors, mini_epsilon, mini_min_neighbors, d_type, path, prot_mode, f_color, f_points, f_red_points, f_green_points, f_density, f_coloc, f_x_angle, f_y_angle, f_size) messagebox.showinfo("Work is DONE!", "You may now enter another session folder.")
def guiXbrlLoaded(cntlr, modelXbrl, attach): if cntlr.hasGui and getattr(modelXbrl, "loadedFromExcel", False): from arelle import ModelDocument from tkinter.filedialog import askdirectory outputDtsDir = askdirectory( parent=cntlr.parent, initialdir=cntlr.config.setdefault("outputDtsDir", "."), title="Please select a directory for output DTS Contents", ) cntlr.config["outputDtsDir"] = outputDtsDir cntlr.saveConfig() if outputDtsDir: def saveToFile(url): if os.path.isabs(url): return url return os.path.join(outputDtsDir, url) # save entry schema dtsSchemaDocument = modelXbrl.modelDocument dtsSchemaDocument.save(saveToFile(dtsSchemaDocument.uri)) for lbDoc in dtsSchemaDocument.referencesDocument.keys(): if lbDoc.inDTS and lbDoc.type == ModelDocument.Type.LINKBASE: lbDoc.save(saveToFile(lbDoc.uri))
def update_files(self): """Update the Calendar with the new files""" self.clear_data_widgets() self._dates.clear() folder = variables.settings["parsing"]["path"] if not os.path.exists(folder): messagebox.showerror("Error", "The specified CombatLogs folder does not exist. Please " "choose a different folder.") folder = filedialog.askdirectory() variables.settings.write_settings({"parsing": {"path": folder}}) return self.update_files() files = [f for f in os.listdir(folder) if Parser.get_gsf_in_file(f)] self.create_splash(len(files)) match_count: Dict[datetime: int] = DateKeyDict() for file in files: date = Parser.parse_filename(file) if date is None: # Failed to parse continue if date not in match_count: match_count[date] = 0 match_count[date] += Parser.count_matches(file) if date not in self._dates: self._dates[date] = list() self._dates[date].append(file) self._splash.increment() self._calendar.update_heatmap(match_count) self.destroy_splash()
def getWorkspacePath(self): """获取项目路径 返回项目路径 """ global IS_DEFAULT_WORKSPACE_PATH global DEFAULT_WORKSPACE_PATH if self.isSelectWorkpacePath == False: # 设置项目地址 if IS_DEFAULT_WORKSPACE_PATH != '1': workspacePath = tkFD.askdirectory(initialdir="/home/",title="选择工作空间") else: workspacePath = DEFAULT_WORKSPACE_PATH self.isSelectWorkpacePath = True self.patchLog.append('\r\n') self.patchLog.append('项目空间位置:' + workspacePath) self.workspacePath = workspacePath return workspacePath return self.workspacePath
def getAFolder(): while 1: #clear screen (cross platform) os.system('cls' if os.name == 'nt' else 'clear') print("To exit the program, press CTRL+C on your keyboard.") print("\nPlease input the location of the folder: ", end="") #create tkinter object tk = tkinter.Tk() #open save file dialog GUI to get filename to save folderLoc = filedialog.askdirectory() #close the mini annoying tk window that will appear too when opening 'save file dialog' tk.destroy() #remove full path of file and get only filename if(folderLoc == ""): continue #display filename print(folderLoc) fileLoc = os.listdir(folderLoc) #remove files that are not text file for i in range(len(fileLoc)): if(fileLoc[i][-4:] != ".txt"): fileLoc.remove(file) else: fileLoc[i] = folderLoc + "/" + fileLoc[i] return fileLoc
def new_thread_1(self): """thread for the first algorythm""" dir_name = filedialog.askdirectory(parent=self, initialdir="/", title='Please select a directory') if dir_name != "": self.disable_menu() self.path_and_bag.check_if_refresh(dir_name) self.config(cursor="wait") self.update() self.clean_queue() GUI.static_queue.put("Finding files in chosen folder:\n\n") num_files = len([val for sub_list in [[os.path.join(i[0], j)for j in i[2]] for i in os.walk(dir_name)] for val in sub_list]) rott = tk.Tk() app = App(rott, GUI.static_queue, num_files) rott.protocol("WM_DELETE_WINDOW", app.on_closing) thread = threading.Thread(target=self.open_menu, args=(dir_name,)) thread.setDaemon(True) thread.start() app.mainloop() else: print("Action aborted")
def get_dir(DialogTitle='Select Directory', DefaultName='.'): ''' Select a directory Parameters ---------- DialogTitle : string Window title DefaultName : string Can be a directory AND filename Returns ------- directory : string Selected directory. Examples -------- >>> myDir = skinematics.ui.getdir('c:\\temp', 'Pick your directory') ''' root = tkinter.Tk() root.withdraw() fullDir = tkf.askdirectory(initialdir=DefaultName, title=DialogTitle) # Close the Tk-window manager again root.destroy() if not os.path.exists(fullDir): return 0 else: print('Selection: ' + fullDir) return fullDir
def openDir(dir): global inDir inDir = askdirectory() print(inDir) dir.delete(0,END) dir.insert(0,inDir) return(inDir)
def setloc(self): if self.type=='dir': self.loc.set(askdirectory()) elif self.type=='file': self.loc.set(askopenfilename()) else: self.loc.set(None)
def browseToFolder(self): """Opens a windows file browser to allow user to navigate to the directory to read returns the file name of the path that was selected """ retFileName = filedialog.askdirectory() print ("Selected Folder: ",retFileName) return retFileName
def file_handler(): '''Prompt the user for the folder path, and read all the files with it.''' #location = input('Please indicate whether right or left you want to label (r, l): ').lower() directory = filedialog.askdirectory() file_list = os.listdir(directory) os.chdir(directory) newfolderpath = directory + '/labeled' if not os.path.exists(newfolderpath): os.mkdir(newfolderpath) for each in file_list: img = cv2.imread(each) #x=60 #y=60 x = int(img.shape[0]/30) y = int(img.shape[1]/30) #print (x1,y1) os.chdir(newfolderpath) font = cv2.FONT_HERSHEY_SCRIPT_SIMPLEX labeled = cv2.putText(img,'Arthuzi@Photography',(x,y-5), font , 1.8, (0,0,0),5) labeled = cv2.putText(img,'Arthuzi@Photography',(x,y), font , 1.8, (255,255,255),6) labeled = cv2.putText(img,'Arthuzi@Photography',(x,y+5), font , 1.8, (0,0,0),4) #labeled = cv2.putText(img,'Arthuzi@Photography',(x,y+8), font , 1.5, (255,255,255),2) newfile = 'l-'+each if os.path.exists(newfolderpath+'/'+newfile): os.remove(newfile) cv2.imwrite(newfile, labeled) os.chdir(directory)
def onSourceButton(self): # stop any on going analysis thread if (self.mAnalyzeThread) and self.mAnalyzeThread.is_alive(): print("stopping thread") self.mStopThreadRequest = True self.mAnalyzeThread.join(1.) # reset the source and destination lists self.uiSourceList.delete(0, END) self.uiDestinationList.delete(0, END) #query user for a new source folder folder = filedialog.askdirectory(title=self.T['SRC_cb_dlg'], mustexist=True, initialdir=self.mSourceFolder ) self.uiSourceValue.set(folder) self.mSourceFolder = folder self.Log("%s: <%s>\n" % (self.T['SRC_cb_log'], self.uiSourceValue.get())) # start the source parsing thread self.mStopThreadRequest = False self.mAnalyzeThread = threading.Thread(target=self.AnalyzeWorkerThread) self.mAnalyzeThread.start()
def openOutDir(dir): global outDir outDir = askdirectory() print(outDir) dir.delete(0,END) dir.insert(0,outDir) return(outDir)
def SelectDataFiles(): """Select the files to compress into a JAM""" # Draw (then withdraw) the root Tk window logging.info("Drawing root Tk window") root = Tk() logging.info("Withdrawing root Tk window") root.withdraw() # Overwrite root display settings logging.info("Overwrite root settings to basically hide it") root.overrideredirect(True) root.geometry('0x0+0+0') # Show window again, lift it so it can recieve the focus # Otherwise, it is behind the console window root.deiconify() root.lift() root.focus_force() # The files to be compressed jam_files = filedialog.askdirectory( parent=root, title="Where are the extracted LEGO.JAM files located?" ) if not jam_files: root.destroy() colors.text("\nCould not find a JAM archive to compress!", color.FG_LIGHT_RED) main() # Compress the JAM root.destroy() BuildJAM(jam_files)
def loadDirectory(): dir = fd.askdirectory() if dir: return readDirectory(dir) return None
def print11(self): if self.valueputin.get() !="": self.valueInput=self.valueputin.get() elif self.valueputin.get()=="": self.valueInput=filedialog.askdirectory() print (self.valueInput) # self.valueInput=filedialog.askdirectory() keyvalue=self.valueInput cmd1=r'git config --global core.quotepath false' cmd2=r'git status' cmd=cmd1 +"&&" +cmd2 print(keyvalue) cmdpath=str(keyvalue) process=subprocess.Popen(cmd,shell=True,cwd=cmdpath,stdout=subprocess.PIPE) stdout=process.communicate() process.wait() result=process.returncode aaa=type(stdout) vv=stdout[0] aa=str(vv,'utf-8') print(str(vv,'utf-8')) L=aa.split('\n') #insert UNTRACKED FILES if aa.find('Untracked files:')>=0: countu=L.index('Untracked files:') print(L.index('Untracked files:')) L=L[countu+3:-3] L2=[x.replace('\t','') for x in L] for i in L2: print(i) self.tree.insert("","end",values=(i)) print(L2) #insert deleted files L3=aa.split('\n') print(L3) for item in L3: if item.find('deleted')>=0: # countd=L3.index('\tdeleted') item=item.split(":")[1] self.tree3.insert("","end",values=(item)) print(item) L4=aa.split('\n') print(L4) for item in L4: if item.find('modified')>=0: # countd=L3.index('\tdeleted') item=item.split(":")[1] self.tree3_2.insert("","end",values=(item)) print(item) self.T.config(state=NORMAL) self.T.insert(END,aa) self.T.config(state=DISABLED) def selectItem(a): curItem=self.tree.focus() zz=self.tree.item(curItem)["values"] print(zz) if zz != "": self.tree2.insert("","end",values=(zz)) self.tree.delete(curItem) # print(tree.identify_row(a)) #输出选中值的特性 self.tree.bind("<ButtonRelease-1>", selectItem) def selectItem2(a): curItem=self.tree2.focus() zz=self.tree2.item(curItem)["values"] if zz != "": print(zz) self.tree.insert("","end",values=(zz)) self.tree2.delete(curItem) #restore deleted files def restorefile(a): curItem=self.tree3.focus() msg=messagebox.askquestion(title="Restore",message="Restore the file?") if msg=='yes': # print(self.valueInput.get()) keyvalue=self.valueInput zz=self.tree3.item(curItem)["values"] print(self.tree3.item(curItem)["values"]) self.tree3.delete(curItem) z=zz[0] cmd=r'git checkout ' cmd=cmd+z process=subprocess.Popen(cmd,shell=True,cwd=cmdpath,stdout=subprocess.PIPE) stdout=process.communicate() process.wait() result=process.returncode #add modified files def add_modify(a): global z self.e1.delete(1.0,END) # self.filemenu2=Menu(self.menubar,tearoff=0) # # self.filemenu2.add_command(label="Restore",command=restore_temp) # self.filemenu2.add_command(label="Add",command=add_temp) # self.menubar.add_cascade(label="Modified",menu=self.filemenu2) curItem=self.tree3_2.focus() zz=self.tree3_2.item(curItem)["values"] if zz != "": msg=messagebox.askquestion(title="Restore modify",message="Restore modified file?") if msg=='yes': # print(self.valueInput.get()) keyvalue=self.valueInput zz=self.tree3_2.item(curItem)["values"] print(self.tree3_2.item(curItem)["values"]) self.tree3_2.delete(curItem) z=zz[0] print(z) # cmd0=r'git config --global core.editor "C:/cygwin/bin/"' cmd1=r'git config --global diff.tool p4merge' cmd2=r'git config --global difftool.prompt false' cmd3=r'git config --global alias.d difftool' cmd4_1=r'git d ' cmd4=cmd4_1+z cmd5=cmd1+"&&"+ cmd2+"&&"+ cmd3+"&&"+cmd4 process=subprocess.Popen(cmd5,shell=True,cwd=cmdpath,stdout=subprocess.PIPE) stdout1=process.communicate() process.wait() result=process.returncode cmd=r'git diff ' cmd=cmd+z cmd5=cmd process=subprocess.Popen(cmd5,shell=True,cwd=cmdpath,stdout=subprocess.PIPE) stdout=process.communicate() process.wait() result=process.returncode print(stdout) vv1=stdout[0] print(vv1) aa1=vv1.decode('cp936') print(aa1) stdout=str(stdout) stdout=stdout[3:-8] print(stdout) L=aa1.split('\n') L=np.array(L) L=L.reshape(-1,1) L=pd.DataFrame(L) print(L) count=1 for i in L.index: a=L.loc[i][0]+"\n" print(a) print(str(count)+".0") if a.find('+')!=-1: print(count) self.e1.insert(INSERT,a) self.e1.tag_add("here",str(count)+".0",str(count)+".50") self.e1.tag_config("here",foreground="red") else: self.e1.insert(INSERT,a) count+=1 return z return zz # top.destroy() # # top = Toplevel() # top.title('Different from last Commit Version') # v1 = StringVar() # buttonc=Button(top,text="Restore") # buttonc.grid(row=0,column=0,padx=10,pady=10) # buttonc.bind("<ButtonRelease-1>",restore_temp) # buttonadd=Button(top,text="Add to commit") # buttonadd.grid(row=0,column=2,padx=10,pady=10) # buttonadd.bind("<ButtonRelease-1>",add_temp) # e1 = Text(top,width=100,height=100) # e1.grid(row=1,column=1,padx=100,pady=100) # cmd=r'git checkout ' # cmd=cmd+z # process=subprocess.Popen(cmd,shell=True,cwd=cmdpath,stdout=subprocess.PIPE) # # stdout=process.communicate() # # process.wait() # result=process.returncode #button binding self.tree2.bind("<ButtonRelease-1>", selectItem2) self.tree3.bind("<ButtonRelease-1>",restorefile) self.tree3_2.bind("<Double-Button-1>",add_modify)
import glob import os from tkinter import * from tkinter import filedialog """ Convert VAMAS files to TXT files (Origin compatible header). Prompts user to pick a directory, and searches subdirectories and converts all found files. Auto-detects ISS or XPS data, and saves it appropriately. Original author: Jakob Ejler Sørensen Modified by: Julius Lucas Needham """ #Ask for input folder and chdir to it. cdir = os.getcwd() files = filedialog.askdirectory(initialdir=cdir) os.chdir(files) for filename in glob.glob('**/*.vms', recursive=True): #Remove any subfolder designation from file name. filename = filename.lstrip('\b') #Check whether files are XPS or ISS, and loads appropriate module, sets marker and prints detected type. if filename.split('_')[3].split('-')[0] == 'XPS': import XPS as module marker = 0 elif filename.split('_')[3].split('-')[0] == 'ISS': import ISS as module marker = 1 #Import VAMAS and save as .txt with header in same folder.
import os from tkinter import Tk from tkinter.filedialog import askopenfilename from tkinter.filedialog import askdirectory from tkinter.simpledialog import askstring from tkinter.simpledialog import askinteger Tk().withdraw() "changer nom orga" BRS = 'BRS' TROD = 'TROD' vislvl = 4 fichier_source = askopenfilename(title='Fichier avec infos structure') folder = askdirectory(title='dossier cible') #tel1=askstring(title = 'téléphone préleveur' , prompt = 'entrer le numéro de téléphone du préleveur') tel1 = '0610101010' dateetab = askstring(title='nom_fichier', prompt='format _AAAAMMJJ_OP') NB = askinteger(title='Avec/Sans PCR jumelle', prompt='1 : uniquement TROD\n2 :TROD + PCR') os.chdir(folder) def extractioncsv(fichiercsv): liste = [] with open(fichiercsv, encoding='cp1252') as fcsv: lecteur = csv.reader(fcsv, delimiter=';') for ligne in lecteur: liste.append(ligne) return liste
import os import nibabel as nib import tkinter as tk from tkinter import filedialog from glob import glob ### PROMPT USER FOR DIRECTORY root = tk.Tk() root.withdraw() dirname = filedialog.askdirectory( parent=root, title='Please select directory you want to convert') if dirname == (): raise ValueError('No directory selected. Aborting!') print(dirname) ### PROMPT USER FOR RECURSIVE OR NOT response = input( 'Do you want to recursively convert every .mnc file in the tree? ') if response not in ('y', 'n', 'Y', 'N', 'Yes', 'No', 'yes', 'no'): raise IOError('Response not recognized') else: if response in ('Yes', 'yes', 'y', 'Y'): ans = True hold = False else: ans = False hold = False ### COLLECT ALL MNCs if ans:
import os import re from cv2_rolling_ball import subtract_background_rolling_ball from astropy.stats import sigma_clip from scipy import ndimage from skimage.measure import profile_line from skimage import io from LineProfile import LineProfile from Fft import Fft from QuadraticFit import QuadraticFit allPixelTemps = [] #User select the folder of images root = Tk() root.withdraw() folderName = filedialog.askdirectory() print(folderName) os.lstat(folderName) #Get the file names of the images fileType = '.csv' fileNames = GetFileNames(folderName, fileType) nFiles = len(fileNames) print(nFiles) print(fileNames) count = 0 allSetTemps = [] for currentFileName in fileNames: #read the csv file
def selectPath(self): self.workPath = askdirectory(initialdir = self.workPath) self.config.set('default', 'nowWorkPath', self.workPath) with open(getcwd() + '/config.ini', 'w') as f: self.config.write(f)
def definePath(): path = askdirectory() return path
return df_out #required for the dialog boxes root = tk.Tk() root.withdraw() # Prepare a dataframe df_merged = pd.DataFrame( columns=['directory', 'image', 'nul', 'single', 'multiple', 'genotype']) #loop until all genotypes are merged go_on = True while (go_on): #ask for a directory dirName = filedialog.askdirectory( title="Choose a folder containing results from 1 genotype") #get filelist and search for chr3 FISH results files filelist = getListOfFiles(dirName) df_out = findAndMerge(filelist) #ask user to specify the genotype genotype = simpledialog.askstring(title=None, prompt="Enter genotype") df_out["genotype"] = genotype df_merged = df_merged.append(df_out, sort=False, ignore_index=True) go_on = messagebox.askyesnocancel(title=None, message="Add another genotype?") #calculate the aneuploidy ratio of spermatids df_merged['aneuploidy ratio'] = ( (2 * df_merged['multiple']) /
def choose_save_directory(self): self.download_location = os.path.abspath(filedialog.askdirectory())
# DocTertiary is html inserted and modifed by python into DocSecondary.\ global DocTimeStamp #timestamp taken at time of document generation in miliseconds global DocName, ImageDir, OutputDir, DocNameFinal #NamePrompt (prompt for custom document name on output)\ #ImageDir (prompt for directory to all the images to be used)\ #OutputDir (Directory that the final document will be output to)\ ExitCond = "n" print("select image directory") while (ExitCond != "y"): ImageDir = 0 #purge ImageDir root = Tk() root.withdraw() root.update() ImageDir = fd.askdirectory() root.destroy() #create and destroy ImageDir root selection file dialog print(ImageDir) ExitCond = input("is the image directory " + ImageDir + " correct (y/n)") #directory confirmation if ExitCond == "no": ExitCond = "n" if ExitCond == "yes": ExitCond = "y" #exit catch incase someone cant see that it means the letters y/n print(ImageDir) #prints the image directory onlyfiles = next(os.walk(ImageDir))[2] ImageNum = (len(onlyfiles))
def browse(self): path: str = self.path_str.get() path = filedialog.askdirectory(initialdir=path, title="Select directory") if path: self.path_str.set(path)
def onBrowse1(self): dir1 = filedialog.askdirectory(initialdir=os.getcwd()) if len(dir1) > 0: source = self.txt_source.insert(0, dir1)
# Stop program if window is closed at OS level ('X' in upper right # corner or red dot in upper left on Mac) root.protocol("WM_DELETE_WINDOW", lambda: cleanup()) # Place all windows close to the center of the screen root.withdraw() root.update_idletasks() x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2 y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2 root.geometry("+%d+%d" % (x, y)) while True: if os.path.isdir('/media'): initial_dir = "/media" else: initial_dir = "/" root.directory = filedialog.askdirectory( mustexist=True, title=f"{__app_name__} {__version__} Select destination", initialdir=initial_dir) if not root.directory: root.quit() break dest_ok, message = validate_destination(root.directory) if dest_ok: root.title(f"{__app_name__} {__version__}") root.deiconify() progress = ttk.Progressbar(root, orient="horizontal", length=350, mode='determinate') progress.pack(pady=10) label = ttk.Label(root, text="Click Start to begin backup",
def browse_directory(): global directory_path directory_path.set(filedialog.askdirectory())
def onBrowse2(self): dir2 = filedialog.askdirectory(initialdir=os.getcwd()) if len(dir2) > 0: destination = self.txt_destination.insert(0, dir2)
from tkinter import filedialog import os from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 from reportlab.lib.pagesizes import portrait dir = filedialog.askdirectory(title="open images") sdir = filedialog.askdirectory(title="where to save") print(sdir) filename = str(sdir) + "/" + "generated_pdf.pdf" c = canvas.Canvas(filename, pagesize=portrait(A4)) for file in os.listdir(dir): if file.endswith(".jpg"): file = dir + "/" + str(file) print(file) c.drawImage(file, 25, 180, width=550, height=500) c.showPage() c.save()
import numpy as np import tkinter as tk from tkinter import filedialog import pandas as pd from pandas import DataFrame import time root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename() # 读取RGB空间的图像 # Cr_csv_path = filedialog.askopenfilename() # Cb_csv_path = filedialog.askopenfilename() # img_csv_path = filedialog.askopenfilename() # face_out_path = filedialog.askopenfilename() dir_path = filedialog.askdirectory() oval_name = dir_path + r'/oval_03.png' img_read = cv2.imread(file_path) # 读取图像内容 img_YCrCb = cv2.cvtColor(img_read, cv2.COLOR_RGB2YCrCb) # 转换色彩空间 # 构建椭圆肤色模型 oval_matrix = np.zeros((256, 256), dtype=np.uint8) # 建立一个用于存储椭圆模型的矩阵 center = (round(113), round(152)) size = (25, 12) angle = -20 color = 255 thickness = np.random.randint(1, 9) img = cv2.ellipse(oval_matrix, center, size, angle, 0, 360, color, thickness=-1) # 取得椭圆肤色模型 # img_csv = DataFrame(img) # img_csv.to_csv(img_csv_path, index=False, header=False, mode='w', decimal=',')
<iframe width="1000" height="450" frameborder="0" seamless="seamless" scrolling="yes" \ src="''' + url_fb + '''.embed?width=800&height=450"></iframe> <br><br>''' + matrix_html + ''' </body> </html>''' nombre = folder_selected + '/Reporte.html' f = open(nombre, 'w') f.write(html_string) f.close() def Report(): df_fb = generate_facebook_df(folder_selected) print('Facebook DF Generated') df_insta = generate_instagram_df(folder_selected) print('Instagram DF Generated') df_f, df_i = slice_df(desde, hasta, df_fb, df_insta) fb_plot_url = generate_engagement_plot_url(df_f, 1) insta_plot_url = generate_engagement_plot_url(df_i, 2) generate_html(fb_plot_url, insta_plot_url, df_f, df_i, folder_selected) root = Tk() root.withdraw() folder_selected = filedialog.askdirectory(title='Escoja el Directorio donde se guararan los archivos') Report()
def selectFolder(): filepath = filedialog.askdirectory() messagebox.showinfo("Selected folder name", filepath)
out_file_PO = path+"\\result\\"+"Grab_all_file_PO_"+tt+".csv" if os.path.exists(out_file_PO): os.remove(out_file_PO) ''' rt = tk.Tk() rt.withdraw() msg.showinfo("Information", "You need to select a working directory ") rt.destroy() #root.quit() rt = tk.Tk() rt.withdraw() out_dir = askdirectory( title= 'Select Directory where file Grab_all_file_PO_MBR ... will be create (delete and recreate if already present ', initialdir=os.getcwd()) rt.destroy() out_file_PO_MBR = out_dir + '/Grab_all_file_PO.csv' if os.path.exists(out_file_PO_MBR): os.remove(out_file_PO_MBR) append_sw = 0 for lv1 in List_seed: tot_PO = [] #arr_tot = np.array([],dtype=np.str) arr_PO = np.array([], dtype=np.str) arrx_PO = np.array([], dtype=np.str) arry_PO_MBR = np.array([], dtype=np.str)
run_writer_end('filesyncer_progress') run_writer_end('m_time_checker_run_file') run_writer_end('m_time_listner_checker_run_file') #Syncing Part Starts here #this part will take care of signing in login() initlogs() #this part of the code will upload the os_file_list() files clientno = input('Enter the client no : ') path = askdirectory(title='Import the folder you want to sync' ) #after done the tinkter window needs to be closed. temppath = os.getcwd( ) + '\\temp_folder_for_syncer' #after done the tinkter window needs to be closed. mtime_logger() def folder_syncer(): folderPaths, filePaths = os_file_list(path) list_writer(folderPaths, 'folderpath' + clientno) #rememeber folderpath. file_upload('folderpath' + clientno + '.txt') #this will upload the files to the drivev. file_delete('folderpath' + clientno +
def select_path(self): self.path=filedialog.askdirectory() self.window.destroy()
def browsemdir(self): path = filedialog.askdirectory(title="Select Mods Folder") if not path: return self.widgets["e_mdir"].delete(0, tk.END) self.widgets["e_mdir"].insert(0, path)
def setSource(): rep = filedialog.askdirectory(initialdir='/tmp') self.vartxtTwo.set(rep)
traceback.print_tb(exc_traceback) timeInSecs = 0xFFFFFFFF strTimeStamp = "" nextLine = "" return timeInSecs, strTimeStamp, msgString if __name__ == '__main__': import os import tkinter as tk from tkinter import filedialog from mcgLogCombiner.mcgLogGlobalVariables import BTCL_LOG_ALL_FILENAME root = tk.Tk() root.withdraw() workingDirectory = filedialog.askdirectory( initialdir="C:/workspace/TWCS/___issues", title="Choose a Issue Archive Directory.") if workingDirectory == "": print("No directory selected!") else: parser = BtclLogParser( os.path.join(workingDirectory, BTCL_LOG_ALL_FILENAME)) if parser.isOk(): parsingOk = parser.getNextLine() while parsingOk[0] < 0xFFFFFFFF: print("timestamp: %d / msg : %s" % (int(parsingOk[0]), parsingOk[2])) parsingOk = parser.getNextLine()
def c_open_dir(): rep = filedialog.askdirectory(initialdir='/tmp') self.vartxtOne.set(rep)
def selectPath(): path_ = askdirectory() path.set(path_)
namex = "job_iter_res" tt = RegEntry(pathx,namex) tt.add_entry('test2') pathx = r'Software\BI_LUM2' namex = "job_iter_res" tt = RegEntry(pathx,namex) file_list = tt.list_entry() ''' main_rt = tk.Tk() main_rt.withdraw() #out_file = askopenfilename(parent=rt) out_dir = askdirectory( title= 'Select Directory where file RESULT_JOB_SQL.CSV will be create (delete and recreate if already present ', initialdir=os.getcwd()) if out_dir == "": sys.exit out_file = out_dir + '/RESULT_JOB_SQL.CSV' if os.path.exists(out_file): os.remove(out_file) in_sql = ''' select trim(dds_dsn) as dsn, trim(DDS_JOBNAME) as JOBNAME,
def choosefile(a): if self.valueputin.get() !="": self.valueInput=self.valueputin.get() else: self.valueInput=filedialog.askdirectory() print (self.valueInput)