Exemple #1
0
def prompt_files():
    """Prompt for the data with Tkinter GUI.

    Returns:
        input_files (list): Full path to the files in a list.
    """

    while True and "dummy_var" not in locals():
        try:
            input_files = []
            root = Tkinter.Tk()
            list_of_files = tkFileDialog.askopenfiles(mode="r",
                                                      **config.dialog_files)
            root.destroy()

            for f in list_of_files:
                input_files.append(f.name)

            if not input_files:
                raise IndexError

            dummy_var = 0

        except IndexError:
            if not query_yes_no("You have not picked any files. Retry?"):
                sys.exit("No files selected.")

    return input_files
Exemple #2
0
def prompt_labjournal():
    """Prompt for Labjournal with Tkinter GUI.

    Returns:
        labj (Pandas DF): Labjournal imported from xlsx file.
        path_labj (str): Full path to the labjournal.
    """

    while True and "labj" not in locals():
        try:
            root = Tkinter.Tk()
            path_labj = tkFileDialog.askopenfiles(mode="rb",
                                                  **config.dialog_labj)
            root.destroy()
            labj = pandas.read_excel(
                path_labj[0],
                sheet_name=config.labj_ws_name,
                dtypes=str,
                converters={"ID": str},
            )

        except IndexError:
            if not query_yes_no("You have not picked any files. Retry?"):
                sys.exit(
                    "No Labjournal specified! You maybe want to change your config."
                )

    return labj, path_labj[0].name
Exemple #3
0
 def open_files(self):
     """
     打开多个文件
     :return: 文件对象
     """
     r5 = tkfd.askopenfiles(title='OpenFiles', **self.options_file)
     print r5
     return r5
Exemple #4
0
 def file_dialog(self):
     self.infiles = tkFileDialog.askopenfiles()
     if len(self.infiles) == 1:
         self.label = Label(self.frame, text=self.infiles[0].name).grid(row=2, pady=8, padx=5)
     else:
         self.label = Label(self.frame, text='Multiple files').grid(row=2, pady=8, padx=5)
     print 'Ready to analyse:'
     for infile in self.infiles:
         print infile.name
     print ''
def read_spreadsheets(file_names=None,
                      csv_delimiter=',',
                      more_than_1=True,
                      tkinter_title="Chose a file"):
    if file_names == None:
        tk = Tkinter.Tk()
        tk.withdraw()
        if more_than_1 == True:
            loaded_files = tkFileDialog.askopenfiles(title=tkinter_title,
                                                     filetypes=[
                                                         ("csv", "*.csv"),
                                                         ("xlsx", "*.xlsx"),
                                                         ('All files', '*.*')
                                                     ])
            file_names = [x.name for x in loaded_files]
        else:
            loaded_file = tkFileDialog.askopenfile(title=tkinter_title,
                                                   filetypes=[
                                                       ("csv", "*.csv"),
                                                       ("xlsx", "*.xlsx"),
                                                       ('All files', '*.*')
                                                   ])
            file_names = [loaded_file.name]
        tk.destroy()
        print file_names
    if not isinstance(file_names, list):
        file_names = [file_names]
    condition_rows_dict = {}
    for file_name in file_names:
        file_type = file_name[-6:]  #Take some extra caracters just in case
        if any(x in file_type for x in [".xlsx", ".xlsm", ".xltx", ".xltm"]):
            print file_type
            wb = load_workbook(file_name, read_only=True, data_only=True)
            for ws in wb.worksheets:
                condition = ws.title
                #
                if "Sheet" in condition:
                    condition = condition.replace("Sheet", "Label_")
                elif "Hoja" in condition:
                    condition = condition.replace("Hoja", "Label_")
                condition_rows_dict[condition] = []
                for xlsx_row in ws.rows:
                    row = []
                    for cell in xlsx_row:
                        row.append(cell.value)
                    condition_rows_dict[condition].append(row)
        else:
            csv_file = open(file_name)
            csv_reader = csv.reader(csv_file, delimiter=csv_delimiter)
            row_list = list(csv_reader)
            condition = (file_name.split(".")[0]).split("/")[
                -1]  #Get the name of the file minus the extension and the path
            condition_rows_dict[condition] = row_list
            csv_file.close()
    return condition_rows_dict
Exemple #6
0
	def open_file(self):
		# set file options
		self.opt = {}
		self.opt["defaultextension"] = ".fbx"
		self.opt["filetypes"] = [("Fbx Files", "*.fbx")]
		
		fbxFiles = tkFileDialog.askopenfiles(mode="rw", **self.opt)
		
		for fbxFile in fbxFiles:
			self.openedFbxFiles.append(fbxFile.name)
			self.item_view.insert("", "end", text=0, values=(os.path.basename(fbxFile.name), fbxFile.name))
Exemple #7
0
 def readTLDR(self, path=None):
     if path == None:
         import tkFileDialog
         path = tkFileDialog.askopenfiles(mode='r', filetypes=[("Word List", ".tldr")])
     else:
         path = [path.encode('utf-8')]
     for f in path:
         wordsInFile = readTLDR(open(f))
         fileName = f.split("/")[-1].split(".")[0]
         self.dictionaryDB.updateWords(wordsInFile, fileName)
     for view in self.views:
         view.notifyDataSetChanged([])
Exemple #8
0
def find_files():
    fdFiles = tkFileDialog.askopenfiles(parent=master,title='Choose a file')
    if len(fdFiles) <= 0:
        status_update('warn', 'No files have been selected')
        btn_move['state'] = 'disabled'
    else:
        popupMenu['state'] = 'disabled'
        for file in fdFiles:
            queue1.append(str(file).split('\'')[1])
        btn_importAll['state'] = 'normal'
        btn_importDate['state'] = 'normal'
        lblAllImport['text'] = '%s' % (displayFiles())
        generateDateCbxList()
Exemple #9
0
def appendUserFiles ( list ):
    '''
    Appends User selected files to a list
    '''
    
    paths = askopenfiles(filetypes=[("Wildcard", "*")])
    if paths == None:
        print "[?] No files chosen. Try again"
        return False
    print "[#] adding args",
    
    for path in paths:
        sys.argv.append(os.path.relpath(path.name))
    return True
Exemple #10
0
 def open_saved_defects(self):
     """ Load Defect object(s) from one file or many files """
     files = fd.askopenfiles(mode='rb',
                             defaultextension='.pydef',
                             initialdir=self.project.dd_pydef)
     for f in files:
         defect = pickle.load(f)
         if defect.__class__ is not pd.Defect:
             mb.showerror('Error',
                          'This file is not a valid file',
                          parent=self)
             continue
         else:
             self.load_defect(defect)
Exemple #11
0
def appendUserFiles(list):
    '''
    Appends User selected files to a list
    '''

    paths = askopenfiles(filetypes=[("Wildcard", "*")])
    if paths == None:
        print "[?] No files chosen. Try again"
        return False
    print "[#] adding args",

    for path in paths:
        sys.argv.append(os.path.relpath(path.name))
    return True
	def getClickerIDResponses(self):

		tkMessageBox.showinfo(
			"OK",
			"You must now specify the file names that contain the downloaded responses from moodle with the student's clicker IDs.");

		clickerIDFileNames = tkFileDialog.askopenfiles(
			mode='r',title='Clicker ID Data Files',
			filetypes=[('csv files', '.csv'),('text files', '.txt'),('Turning Point ID','.tplx'),('All Files','.*')]
			)


		# Go through each file name and append it to the model that
		# contains the sections file names.
		clickerIDs = {}
		for fileName in clickerIDFileNames:
			if(self.DEBUG):
				print("Selected filenames {0}".format(fileName.name))

			if(self.tplxExtension.search(fileName.name)) :
					sectionInformation = TurningPointClassList()
					sectionInformation.parseFile(fileName.name)
					clickerIDs = sectionInformation.getClassList()

			else:
					rowReader = csv.reader(fileName,delimiter=',')
					lineNumber = 0
					for line in rowReader:

						if(lineNumber==0):
						   # This is the header
						   clickerIDDialog = QueryTurningPointIDFile(self,line,self.lastSlash.sub('',fileName.name))
						   self.wait_window(clickerIDDialog.top)
						   try:
							   emailColumn	 = line.index(clickerIDDialog.getEmailChoice())
							   clickerColumn = line.index(clickerIDDialog.getDeviceIDChoice())
						   except ValueError:
							   break
						   #print("Email: {0} ClickerID: {1}".format(emailColumn,clickerColumn))

						else:
							clickerIDs[line[clickerColumn].upper()] = self.emailAt.sub('',line[emailColumn])
							#print("id: {0}".format(line[emailColumn]))


						lineNumber += 1

		return(clickerIDs)
Exemple #13
0
def read_spreadsheets(file_names=None,csv_delimiter=',',more_than_1=True,tkinter_title="Chose a file"):
    if file_names==None:
      tk=Tkinter.Tk()
      tk.withdraw()
      if more_than_1==True:
         loaded_files = tkFileDialog.askopenfiles(title=tkinter_title,filetypes=[("csv","*.csv"),("xlsx","*.xlsx"),('All files','*.*')]) 
         file_names=[x.name for x in loaded_files]
      else:
         loaded_file = tkFileDialog.askopenfile(title=tkinter_title,filetypes=[("csv","*.csv"),("xlsx","*.xlsx"),('All files','*.*')])  
         file_names=[loaded_file.name]
      tk.destroy()
      print file_names  
    if not isinstance(file_names,list):
       file_names=[file_names]
    condition_rows_dict={}
    for file_name in file_names:
        file_type=file_name[-6:] #Take some extra caracters just in case
        if any(x in file_type for x in [".xlsx",".xlsm",".xltx",".xltm"]):
           print file_type
           wb = load_workbook(file_name, read_only=True,data_only=True)
           for ws in wb.worksheets:
                  condition=ws.title
                  #
                  if "Sheet" in condition:
                     condition=condition.replace("Sheet","Label_")
                  elif "Hoja" in condition:
                     condition=condition.replace("Hoja","Label_") 
                  condition_rows_dict[condition]=[]
                  for xlsx_row in ws.rows:
                      row=[]
                      for cell in xlsx_row:
                          row.append(cell.value)
                      condition_rows_dict[condition].append(row)
        else:
           csv_file=open(file_name)
           csv_reader=csv.reader(csv_file,delimiter=csv_delimiter)
           row_list=list(csv_reader)
           condition=(file_name.split(".")[0]).split("/")[-1] #Get the name of the file minus the extension and the path
           condition_rows_dict[condition]=row_list
           csv_file.close() 
    return condition_rows_dict
    def choose_files(self):
        selected_files = tkFileDialog.askopenfiles('r')

        if len(selected_files) < 1:
            return

        # clear the canvas and the relevant file_dict keys
        self.file_list_canvas.delete(Tkinter.ALL)
        for k in self.file_list_canvas.children.keys():
            file_path = self.file_list_canvas.children[k].file_path
            del(self.file_dict[file_path])
            del(self.file_list_canvas.children[k])

        for i, f in enumerate(selected_files):
            cb = MyCheckbutton(
                self.file_list_canvas,
                text=os.path.basename(f.name),
                file_path=f.name
            )

            try:
                chosen_file = ChosenFile(f, cb)
            except TypeError:
                del cb
                continue

            # bind to our canvas mouse function
            # to keep scrolling working when the mouse is over a checkbox
            cb.bind('<MouseWheel>', self._on_mousewheel)
            self.file_list_canvas.create_window(
                10,
                (24 * i),
                anchor='nw',
                window=cb
            )

            self.file_dict[chosen_file.file_path] = chosen_file

        # update scroll region
        self.file_list_canvas.config(
            scrollregion=(0, 0, 1000, len(selected_files)*20))
	def addGrades(self,defaultFile=None) :
		# method for adding file names to the list of grade files to
		# be read.
		#print("Add grades")

		fileTypes = [('csv files', '.csv'),
					 ('xml files', '.xml'),
					 ('text files', '.txt'),
					 ('tpzx files', '.tpzx'),
					 ('all files', '.*')]

		if(self.DEBUG):
			fileTypes = [('tpzx files', '.tpzx'),
						 ('csv files', '.csv'),
						 ('xml files', '.xml'),
						 ('text files', '.txt'),
						 ('all files', '.*')]


                if(defaultFile):
                    selectedFilenames = [open(defaultFile,'r')]
                else:
                    selectedFilenames = tkFileDialog.askopenfiles(
                        mode='r',title='Data Files',
                        filetypes=fileTypes
                        )


		# Go through each file name and append it to the model that
		# contains the sections file names.
		for fileName in selectedFilenames:
			if(self.DEBUG):
				print("Selected filenames %{0}".format(fileName))
				
			# Add the file name to the widget 
			self.gradeListBox.insert(END,fileName.name)

			# Set the default number of lines to skip at the top of the file.
			if(fileName not in self.headerLineSkip) :
				self.setSkipAmount(fileName.name,0)
	def addSections(self,defaultFile=None) :
		# method for adding file names to the list of section files to
		# be read.
		#print("Add grades")
                if(defaultFile):
                    selectedFilenames = [open(defaultFile,'r')]
                else:
                    selectedFilenames = tkFileDialog.askopenfiles(
                        mode='r',title='Data Files',
                        filetypes= [('csv files', '.csv'),
                            ('xml files', '.xml'),
                            ('text files', '.txt'),
                            ('all files', '.*')]
			  ) 


		# Go through each file name and append it to the model that
		# contains the sections file names.
		for fileName in selectedFilenames:
			if(self.DEBUG):
				print("Selected filenames %{0}".format(fileName))
			self.sectionListBox.insert(END,fileName.name)
# 询问文件名
# askopenfilename(**options)
if 0:
    file_name = tkFileDialog.askopenfilename()
    print(file_name)

# 询问文件名列表 多选
# askopenfilenames(**options)
if 0:
    file_list = tkFileDialog.askopenfilenames()
    print(file_list)

# 询问文件名列表 返回文件对象列表
# askopenfiles(mode='r', **options)
if 0:
    file_obj_list = tkFileDialog.askopenfiles()
    print(file_obj_list)

# 询问保存文件地址 返回文件对象
# asksaveasfile(mode='w', **options)
if 0:
    file_obj = tkFileDialog.asksaveasfile()
    print(file_obj)
    file_obj.close()

# 询问保存文件地址 返回文件名
# asksaveasfilename(**options)
if 0:
    file_name = tkFileDialog.asksaveasfilename()
    print(file_name)
Exemple #18
0
import os.path

plt.close('all')


## Filter-Funktion
def filt(sig):
    b, a = signal.ellip(4, 0.01, 120, 0.125)
    out = signal.filtfilt(b, a, sig)
    return out


## Dateien einlesen und Funktion anwenden
# asdDir=r"D:\Files\Backup\Google Drive\Transfer\Python"
asdDir = r"C:\Users\Bob-Lap\Google Drive\Transfer\Python"
dateilist = fd.askopenfiles(initialdir=asdDir, title='Messdatei auswählen')

verlauf = np.zeros(np.size(dateilist))
filverlauf = np.zeros(np.size(dateilist))

i = 0
for datei in dateilist:  # Durchläuft alle Dateien

    # verlauf[i]=np.loadtxt(datei.name)   # Lädt Werte
    verlauf = np.loadtxt(datei.name)  # Lädt Werte

    datei.close()
    # filverlauf[i]=filt(verlauf[i]) # Filter-Funktion
    filverlauf = filt(verlauf)
    i += 1
Exemple #19
0
def run():
    " Main procedure "

    tkObj = Tkinter.Tk()
    tkObj.file_opt = options = {}
    options['defaultextension'] = '.csv'

    openFiles = tkFileDialog.askopenfiles('r')
    fi = 0
    if openFiles:
        for fileObj in openFiles:
            fileName = os.path.basename(fileObj.name).split('.')[0]
            fileExt = os.path.splitext(fileObj.name)[1]
            if fileExt != '.csv':
                continue

            # Read data
            data = np.genfromtxt(fileObj.name, dtype = float, delimiter = ',', names = True)

            # time, dista0, distClick0, inrange, inBox
            # tIX, tIY, kIX, kIY, tTX, tTY, kTX, kTY, smoothX, smoothY
            # mouse_flg, mouseState, clickX, clickY

            color = ['y.-', 'b.-', 'c.-', 'k.-', 'g.-', 'r.-', 'm.-','yx-','bx-','cx-','kx-']

            # Plot all data
            keys = ['dista0', 'distClick0', 'inRange', 'inBox', 'tIX', 'tIY', 'kIX', 'kIY', \
            'tTX', 'tTY', 'kTX', 'kTY', 'smoothX', 'smoothY', 'mouse_flg', 'mouseState', 'clickX', 'clickY']
            # for i in range(len(keys)):
            #     figure(fi)
            #     fi += 1
            #     plot(data['time'], data[keys[i]], color[i % len(color)])
            #     title('{}-{}'.format(str(fileName), str(keys[i])))

            # Plot selected data
            selData = data[:]
            keyX = ['distClick0', 'tIX', 'kIX', 'tTX', 'kTX', 'smoothX', 'mouse_flg', 'mouseState', 'clickX']
            figure(fi)
            fi += 1
            for i in range(len(keyX)):
                if keyX[i] == 'mouseState' or keyX[i] == 'mouse_flg':
                    ms = np.array(selData[keyX[i]]) * 500
                    plot(selData['time'], ms, color[i % len(color)], label = keyX[i])
                else:
                    plot(selData['time'], selData[keyX[i]], color[i % len(color)], label = keyX[i])
            title('{}-{}'.format(str(fileName), 'X'))
            legend(loc = 'lower right')

            # keyY = ['distClick0', 'tIY', 'kIY', 'tTY', 'kTY', 'smoothY', 'mouseState', 'clickY']
            keyY = ['distClick0', 'tIY', 'smoothY', 'tIX', 'smoothX', 'mouse_flg', 'mouseState']
            figure(fi)
            fi += 1
            for i in range(len(keyY)):
                if keyY[i] == 'mouseState' or keyY[i] == 'mouse_flg':
                    ms = np.array(selData[keyY[i]]) * 500
                    plot(selData['time'], ms, color[i % len(color)], label = keyY[i])
                else:
                    plot(selData['time'], selData[keyY[i]], color[i % len(color)], label = keyY[i])
            
            # Plot diff
            # ledDiffMean = (np.diff(selData['tIY']) + np.diff(selData['kIY']) + np.diff(selData['tTY']) + np.diff(selData['kTY'])) / 4 * 100
            # ledDiffMean = np.sqrt((np.diff(selData['tIY']) ** 2 + np.diff(selData['tIX']) ** 2)) * 100
            ledDiffMean = np.sqrt((np.diff(selData['smoothY']) ** 2 + np.diff(selData['smoothX']) ** 2))


            diffTime = selData['time'][1:]
            plot(diffTime, ledDiffMean, 'g-', label = 'diff^2')

            tmp = np.sum(ledDiffMean[0:5])
            diffBuff  = np.zeros(len(ledDiffMean) - 4)
            diffBuff[0] = tmp / 5
            for i in range(5, len(ledDiffMean)):
                tmp = tmp - ledDiffMean[i-5] + ledDiffMean[i]
                diffBuff[i - 4] = tmp / 5
            buffTime = selData['time'][5:]
            # plot(buffTime, diffBuff, 'b-', label = 'diff buff * 100')

            diffThumbIndex = np.abs((np.diff(selData['tTY']) + np.diff(selData['kTY']) - np.diff(selData['tIY']) - np.diff(selData['kIY'])) / 4 * 100)
            # plot(diffTime, diffThumbIndex, 'r-', label = '(thumbDiff - indexDiff) * 100')

            # plot the speed
            figure(fi)
            fi += 1
            key = ['mouseState', 'speed', 'buffSize']
            for i in range(len(key)):
                plot(selData['time'], selData[key[i]], color[i % len(color)], label = key[i])
            
            # size: a + b * speed
            # P1(minSpeed, maxBuff), P2(maxSpeed, minBuff)
            maxSpeed = 25
            minSpeed = 0.1
            maxBuff = 35
            minBuff = 10
            paramB = float(minBuff - maxBuff) / (maxSpeed - minSpeed)
            paramA = maxBuff - paramB * minSpeed
            
            size = paramA + paramB * np.array(selData['speed'])
            size = [int(x) for x in size]
            sizeLimit = [min(max(x, minBuff), maxBuff) for x in size]
            plot(selData['time'], sizeLimit, color[3], label = 'size = {} + {} * speed'.format(str(paramA), str(paramB)))

            title('{}-{}'.format(str(fileName), 'Y'))
            legend(loc = 'upper right')

            show()
Exemple #20
0
 def add_models(self):
     files = tkFileDialog.askopenfiles()
     self.files.append(files)
     for f in files:
         self.groups.insert(tk.END, f.name.split("/")[-1] + "\n")
# 询问文件名
# askopenfilename(**options)
if 0:
    file_name = tkFileDialog.askopenfilename()
    print(file_name)

# 询问文件名列表 多选
# askopenfilenames(**options)
if 0:
    file_list = tkFileDialog.askopenfilenames()
    print(file_list)

# 询问文件名列表 返回文件对象列表
# askopenfiles(mode='r', **options)
if 0:
    file_obj_list = tkFileDialog.askopenfiles()
    print(file_obj_list)

# 询问保存文件地址 返回文件对象
# asksaveasfile(mode='w', **options)
if 0:
    file_obj = tkFileDialog.asksaveasfile()
    print(file_obj)
    file_obj.close()

# 询问保存文件地址 返回文件名
# asksaveasfilename(**options)
if 0:
    file_name = tkFileDialog.asksaveasfilename()
    print(file_name)