Exemple #1
0
    def add_track(self):                                
        """
        Opens a dialog box to open files,
        then stores the tracks in the playlist.
        """
        # get the filez
        if self.options.initial_track_dir=='':
        	    filez = tkFileDialog.askopenfilenames(parent=self.root,title='Choose the file(s)')
        	
        else:
        	    filez = tkFileDialog.askopenfilenames(initialdir=self.options.initial_track_dir,parent=self.root,title='Choose the file(s)')
        	    
        filez = self.root.tk.splitlist(filez)
        for file in filez:
            self.file = file
            if self.file=="":
                return
            self.options.initial_track_dir = ''
            # split it to use leaf as the initial title
            self.file_pieces = self.file.split("/")
            
            # append it to the playlist
            self.playlist.append([self.file, self.file_pieces[-1],'',''])
            # add title to playlist display
            self.track_titles_display.insert(END, self.file_pieces[-1])
	
	# and set the selected track
	if len(filez)>1:
	    index = self.playlist.length() - len(filez)
	else:
	    index = self.playlist.length() - 1
	self.playlist.select(index)
	self.display_selected_track(self.playlist.selected_track_index())
Exemple #2
0
def askopenfilenames(*args, **kwargs):
    """
    Wrap the askopenfilenames dialog to fix the fname list return
    for Windows, which returns a formatted string, not a list.
    """
    fnames = tkFileDialog.askopenfilenames(*args, **kwargs)
    return fix_list(fnames)
Exemple #3
0
def selectFiles():
    fnameEncode = tkFileDialog.askopenfilenames(filetypes=[('Excel file', '*.xls;*.xlsx')], multiple=1)
    #sysencode = sys.getfilesystemencoding()
    #fnameDecode = fnameEncode.encode(sysencode)
    #fnameTmpArray = root.tk.splitlist(fnameEncode)
    #fnameArray = [unicode(i, encoding=sysencode) for i in fnameTmpArray]
    print fnameEncode
Exemple #4
0
def vyberSouboruu():  
    #print u"tak jsem uvnitø funkce a právì tisknu tuto vìtu :-)"
    import tkFileDialog  
    nazev=tkFileDialog.askopenfilenames(filetypes=(('image files', '*.jpg *.png *.gif'), ('all files', '*.*')))
    #print nazev
    vstup.delete(0, END)
    vstup.insert(0, nazev)  
def getPaths(default_directory):
    path_list=[]
    origDir=os.getcwd()
    try:
        os.chdir(default_directory)
    except:
        pass
    root=Tkinter.Tk()                           ##  Explicitly call the root window so that you can...
    root.withdraw()                             ##  withdraw it!
    filePaths=tkFileDialog.askopenfilenames()    ##  imageFile will store the filename of the image you choose

    matched=1
    regex="{.*?}"
    start_index=0
    while matched==1:
        filePaths=filePaths[start_index:]
        try:
            match=re.search(regex,filePaths).group()
            start_index=len(match)
            path_list.append(match[1:-1])
        except:
            #print "GetPaths was excepted"
            matched=0    
    
    #path_list.append(filePath)
    root.destroy()                              ##  Some overkill
    os.chdir(origDir)                           ##  Change dir back for net zero change
    return path_list
 def loadFromJSON(self):
     flist = tkFileDialog.askopenfilenames(title="Open captions file...",
                                          filetypes = [("JSON file", "*.json"),
                                                       ("All files", "*")],
                                          initialfile = "captions.json",
                                          multiple = False)
     if flist:  
         name = compatibleFileDialogResult(flist)[0]
     try:
         f = open(name)
         str = f.read()
         f.close()
         try:
             cap = fromJSON(str)
         except ValueError:
             showerror(title = "Error:",
                       message = "file: "+name+" is malformed!")                
         if type(cap) == type({}):
             self.album.captions = cap
             caption = self.album.getCaption(self.selection)
             self.textedit.delete("1.0", END)
             self.textedit.insert(END, caption)                
         else:
             showerror(title = "Error:",
                       message = "file "+name+" does not contain a\n"+
                                 "captions dictionary")                
     except IOError:
         showerror(title = "Error:",
                   message = "could not read file: "+name)
Exemple #7
0
 def onSelect(self):
     menu = self.fileMenu["menu"]
     menu.delete(0, "end")
     paths = tkFileDialog.askopenfilenames(parent=self)
     if len(paths) > 0:
         map(self.fileGroup.addFile,paths)
         self.resetFileMenu(paths,0)
Exemple #8
0
 def _add_mdout(self):
    """ Get open filenames """
    fnames = askopenfilenames(title='Select Mdout File(s)', parent=self,
                              filetypes=[('Mdout Files', '*.mdout'),
                                         ('All Files', '*')])
    for f in fnames:
       self.mdout += AmberMdout(f)
Exemple #9
0
	def open_previous_files(self):
		"""Allows the user to select files from previously running an analysis."""
		if len(self.display_list)>0:
			answer = tkMessageBox.askokcancel(message = "Are you sure you want to load new PDB files? Current workspace will be lost.")
			if answer is False:
				return
			else: 
				del files_list[:]
				print "####   Started a new project    ####"
		self.display_list=[]
		list_filename_paths = tkFileDialog.askopenfilenames(parent=root,title="Select multiple files (by holding SHIFT or CTRL).", filetypes=[("PDB files","SARA_*.pdb"),("All files","*")] )
		if len(list_filename_paths)==0:
			return
		for each_file in list_filename_paths:
			filename=os.path.basename(each_file)[5:-4]
			print >> sys.stderr, "Loaded %s"% filename   
			if each_file not in files_list:
				files_list.append(each_file)
			if filename not in self.display_list:
				self.display_list.append(filename)
		#Sort the list by id
		self.display_list.sort(key=lambda x: x)
		#Add the identifiers to the list
		self.pdb_id_listbox.delete(0, Tkinter.END)
		index = 1
		for record in self.display_list:
			self.pdb_id_listbox.insert(index, record.upper())	
			index+=1
		print "Loaded %d files from previous analysis." % len(files_list)
def SelectBDFs():
    FilesSelected = tkFileDialog.askopenfilenames(title = "Select File(s)", filetypes=[("allfiles","*")] )
    FilesSelected = Fix_askopenfilenames1( FilesSelected )
    #print "--SelectFilesForCSV(in DEF)[after fix]:"
    #for i in FilesSelected:
    #    print i
    BDFin.set( FilesSelected )   
Exemple #11
0
	def __load_genepop_files( self ):

		s_current_value=self.__genepopfiles.get()

		#dialog returns sequence:
		q_genepop_filesconfig_file=tkfd.askopenfilenames(  \
				title='Load a genepop file' )

	
		if len( q_genepop_filesconfig_file ) == 0:
			return
		#end if no files selected

		#string of files delimited, for member attribute 
		#that has type tkinter.StringVar
		s_genepop_files=DELIMITER_GENEPOP_FILES.join( \
								q_genepop_filesconfig_file )
		self.__genepopfiles.set(s_genepop_files)

		self.__init_interface()
		self.__load_param_interface()
		self.__set_controls_by_run_state( self.__get_run_state() )

		if VERY_VERBOSE:
			print ( "new genepop files value: " \
					+ self.__genepopfiles.get() )
		#end if very verbose

		return
def read_matfile(infiles=None):
    """function to read in andrew's matlab files"""
    master=Tk()
    master.withdraw()
    if infiles==None:
        infiles=tkFileDialog.askopenfilenames(title='Choose one or more matlab TOD file',initialdir='c:/ANC/data/matlab_data/')
        infiles=master.tk.splitlist(infiles)
    data_arrays=np.zeros(0)
    datad={}
    vlowarray=[]
    vhiarray=[]
    gainarray=[]
    for filename in infiles:
        #print filename
        mat=scipy.io.loadmat(filename)
        toi=-mat['out']['V1'][0][0][0]/(mat['out']['Vb'][0][0][0][0]-mat['out']['Va'][0][0][0][0])
        gainarray.append(1.)
        vlowarray.append(mat['out']['Va'][0][0][0][0])
        vhiarray.append(mat['out']['Vb'][0][0][0][0])
        samplerate=np.int(1/(mat['out']['t'][0][0][0][1]-mat['out']['t'][0][0][0][0]))
        data_arrays=np.concatenate((data_arrays,toi),axis=0)
    datad['data']=data_arrays
    datad['samplerate']=samplerate
    datad['gain']=np.array(gainarray)
    datad['v_low']=np.array(vlowarray)
    datad['v_hi']=np.array(vhiarray)
    return datad
Exemple #13
0
def CallSigCal(root_window,calcon_in):
    selectedType=DataFormat.get()

    myFormats = [
    ('Miniseed files','*.mseed'),
    ('SAC files','*.sac'),
    ('CSS files','*.wfd'),
    ('All files','*.*')
    ]

    filez = tkFileDialog.askopenfilenames(parent=root_window,title='Use <shift> or <CTRL> to select the data files to include for processing:', \
            initialdir=calcon_in['target_dir'], \
            filetypes=myFormats)

# convert from unicode to str file list
    files = []
    for file in filez:
        files.append(string.replace(str(file), "/", "\\"))
  
#   make sure CalCon is loaded    
    LoadCalCon(calcon_in)
#   show CalCon structure contents before calculation for troubleshooting
    print '\n*** Start Signal Calibration ***'
    print calcon_in  
# call sigcal with list    
    MDTcaldefs.sigcal(calcon_in,files)
Exemple #14
0
def browse():
	global filez
	filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
	entry = ''
	for fil in filez:
		entry =entry+fil+", "
	fileEntry.set(entry)
Exemple #15
0
 def browseFiles(self):
     longFileNameList = tkFileDialog.askopenfilenames(initialdir=self.currentFileDir, title="Load files")
     longFileNameList = list(self.parent.tk.splitlist(longFileNameList))
     if longFileNameList:
         longFileNameList = [os.path.normpath(p) for p in longFileNameList]
         self.currentFileDir = os.path.dirname(longFileNameList[0])
         self.loadFiles(longFileNameList)
Exemple #16
0
 def input_screen_shot(self):
     filename = tkFileDialog.askopenfilenames(filetypes=[("image file", ("*.jpg", "*.png"))])
     for every_filename in filename:
         raw_screen_shot_img = cv2.imread(every_filename)
         if raw_screen_shot_img is not None:
             screen_shot_img = self.remove_edge(raw_screen_shot_img)
             self.raw_screen_shot.append(raw_screen_shot_img)
Exemple #17
0
    def on_import_button(self):
        """ Method called when the import button in the toolbar is pressed. """
        filenames = tkFileDialog.askopenfilenames(filetypes=[("Word List", ".tldr")])

        for filename in filenames:
            try:
                with open(filename, "r") as f:
                    list_Id = database.add_list(filename)
                    data = list(parse_tldr(f))  
                    for word in data:
                        try:
                            word_Id = database.add_word(word.word,
                                                        word.definition,
                                                        word.example,
                                                        word.difficulty)
                        except Exception:
                            pass
                        else:
                            database.add_wordlist_mappings(list_Id, word_Id)
            except IOError as e:
                tkMessageBox.showwarning(
                    "Import Error",
                    "Could not open {0}".format(filename)
                )
                logging.warn(e)  
            else:
                self.view.left_list.model[os.path.relpath(filename)] = data
        self.populate()
def merge_dictionaries():
    global student_dict,student
    #Similar code as above, although the point here would be to merge past student grades dictionary
    # with the sample transcript
    name=askopenfilenames()
    student_data=[]  # Will contain a list of tuples with selected student names and name of files
    student_info={}
    for i in range(len(name)):
        address=name[i]
        filename=""
        for i in range(len(address)-1,-1,-1):
            if address[i]=='/':
                break
            filename+=address[i]
        filename=filename[::-1].encode('ascii')
        student_name=filename.split('.')[0].encode('ascii')
        student_data.append((student_name, filename))

    for student_name,filename in student_data:
        student_info.setdefault(student_name,{})
        student_info[student_name]=grades_dictionary(filename)
    #Here we are able to extract the user/student name that we will merge with past student grades
    # Effectively we create one dictionary with all the data we need
    student = student_data[0][0]
    student_dict[student]=student_info[student]
    print student_dict
def askOpenFileNames():
	global fileNames
	fileNames = tkFileDialog.askopenfilenames(parent=root)
	#txt_File.delete(0, END)
	if fileNames:
		#txt_File.insert(0, fileNames)
		vIn.set(fileNames)
Exemple #20
0
def getInputFileNamesGui():
    ftypes = [("All files", ".bin")]
    master = Tkinter.Tk()
    master.withdraw() # hiding tkinter window
    InputFile = tkFileDialog.askopenfilenames(title="Choose input .bin file", filetypes=ftypes)
    
    return InputFile    
Exemple #21
0
def getImages():
  images = []
  
  # only allow jpgs
  #options = {}
  #options['filetypes'] = [('JPG files', '*.jpg')]
  
  # ask the user to select the images to process
  Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
  # files = askopenfiles(mode="r", **options) # show an "Open" dialog box and return a list of files
  filenames = askopenfilenames() # show an "Open" dialog box and return a list of files
  filenames = filenames.split() # work around for windows python bug: http://bugs.python.org/issue5712
  
  for filename in filenames:
    print filename
    try:
      im = Image.open(filename)
      images.append(im)
      # images must be the same size
      assert(images[0].size[0] == im.size[0])
      assert(images[0].size[1] == im.size[1])
    except:
      break

  # the user must have select 2 or more images
  assert(len(images) > 1)

  return images
def asker(MainProgWin_instance): # аргумент - MainProgWin_instance
    op = askopenfilenames() # тут получаем список файлов, который обрабатываем дальше
    try:
        if type(op) == unicode: # вариант для виндовса
                if op != '':
                        m = re.search('\\{.*?\\}', op, flags = re.I|re.U)
                        if m != None:
                            addresses = re.findall('\\{(.*?)\\}', op, flags = re.I|re.U)
                            addresses = [j for j in addresses if re.search('\\.pyw?$', j, flags = re.I) != None]
                            # проверка файлов на открывабельность
                            for counter in addresses:                                       
                                    MainProgWin_instance.AddFile(counter) # если всё читается,
                                    # то добавляем в массив эту фигню
                        else:
                            MainProgWin_instance.AddFile(op)
                else:       #такого быть не должно, потому что что-то мы выбрали.
                            #а если не выбрали, то список не нуждается в изменении
                    pass 
        else: # для макоси, она выдает результат-кортеж
                for j in op: # перебираем элементы кортежа
                        if re.search('\\.pyw?$', j, flags = re.I) != None:
                                 MainProgWin_instance.AddFile(j)
    except:
       # print u'В функции asker, good_interface.py, произошла непредвиденная ошибка.'
       pass
    MainProgWin_instance.norepeating()
    if MainProgWin_instance.Chosen != 0:
        MainProgWin_instance.choosefiles_button.configure(text = MainProgWin_instance.names.nonullf)
        MainProgWin_instance.choosedir_button.configure(text = MainProgWin_instance.names.nonulld)
        MainProgWin_instance.start_or_exit.configure(text = MainProgWin_instance.names.gobutton, command = (lambda: run_main_part(MainProgWin_instance)))
        t = MainProgWin_instance.FileText()
        MainProgWin_instance.filewindow.delete('1.0', END)
        MainProgWin_instance.filewindow.insert('1.0', t)
Exemple #23
0
    def load_data(self):
        

        
        files = tkFileDialog.askopenfilenames(title='Choose files')
        filelist = list(files)
        for filename in filelist:
            if os.path.splitext(filename)[1] == ".p":
                with open(filename, "rb") as openfile:
                    
                    self.processedList.delete(0, tk.END)
                    self.selectedBlocks.delete(0, tk.END)
                    
                    Data.clear_all()
                    
                    self.re_graph()
                    
                    loaded_data = pickle.load(openfile)
                    
                    Data.grand_amps = loaded_data['grand_amps']
                    Data.orient_amplitudes = loaded_data['orient_amplitudes']
                    Data.grand_avgs = loaded_data['grand_avgs']
                    Data.orient_avgs = loaded_data['orient_avgs']
                    Data.total_avgs = loaded_data['total_avgs']
                    Data.total_amplitudes = loaded_data['total_amps']
                    Data.stim_avgs = loaded_data['stim_avgs']
                    
                    for a, b in enumerate(Data.grand_amps):
                        self.processedList.insert(a, b)
                    
                    for a, b in enumerate(Data.stim_avgs):
                        for c in Data.stim_avgs[b]:
                            for i in range(len(Data.stim_avgs[b][c])):
                                if orientations[c][1] == "flip":
                                    self.selectedBlocks.insert(tk.END, orientations[c][0] + " " + str(i+1) + "  " + b)
Exemple #24
0
 def open_files(self):
     filetypes = [('All files', '.*'), ('Comic files', ('*.cbr', '*.cbz', '*.zip', '*.rar', '*.pdf'))]
     f = tkFileDialog.askopenfilenames(title="Choose files", filetypes=filetypes)
     if not isinstance(f, tuple):
         f = self.master.tk.splitlist(f)
     self.filelist.extend(f)
     self.refresh_list()
	def loadParty(self):
		load_files = tkFileDialog.askopenfilenames(title='Choose which party members to add', initialdir='save_files/',filetypes=[('', '*.ddchar')])
		for load_file in load_files:
			name = load_file
			print name

		return
Exemple #26
0
def Open(location = None):
    global text
    global currentFile
    global password

    if "instance" in str(type(location)):
        location = None

    if location == None:
        openlocation = tkFileDialog.askopenfilenames()[0]
    else:
        openlocation = location

    if openlocation == "":
        return
    
    GetPassword()

    if not decrypt(openlocation, "temp", password):
        print "Bad password"
        RemoveTemp()
        return

    with open("temp", "r") as file1:
        data = file1.read()
    
    RemoveTemp()

    text.delete(1.0, END)
    text.insert(CURRENT, data)
    currentFile = openlocation
    def chooseFile(self):
       
        
        filez = tkFileDialog.askopenfilenames()
        splitFilez = self.tk.splitlist(filez)
        tex.insert(tk.END,'============================================================================\n')
        tex.insert(tk.END,'Adding File\n')
        tex.see(tk.END)
        tex.update_idletasks()
        for item in splitFilez :
            print "ADD %s" %item
            tex.insert(tk.END,'{}  Added\n'.format(item))
            tex.see(tk.END)
            tex.update_idletasks()
            openIt = open(item,'r')
            allFile.append(item) #each file
##            self.checkEnd(item)
##            file_contents = openIt.read()
##            print file_contents
##            loadT.append(file_contents)
##            openIt.close()
##        a = ''.join(loadT)
##        b =  a.rstrip()
##        for word in word_tokenize(b):
##            try:
##        loadTr.append(word)
        tex.insert(tk.END,'Adding Completed \n')
        tex.insert(tk.END,'============================================================================\n')
        tex.see(tk.END)
        tex.update_idletasks()
        checkLoad.append('a')
Exemple #28
0
    def runOpenFileDialog(self,title,filetypes,defaultextension,multiple=False):

        """Create and run an Tkinter open file dialog ."""

        # __pychecker__ = '--no-argsused' # defaultextension not used.

        initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd())

        if multiple:
            # askopenfilenames requires Python 2.3 and Tk 8.4.
            version = '.'.join([str(sys.version_info[i]) for i in (0,1,2)])
            if (
                g.CheckVersion(version,"2.3") and
                g.CheckVersion(self.root.getvar("tk_patchLevel"),"8.4")
            ):
                files = tkFileDialog.askopenfilenames(
                    title=title,filetypes=filetypes,initialdir=initialdir)
                # g.trace(files)
                return list(files)
            else:
                # Get one file and return it as a list.
                theFile = tkFileDialog.askopenfilename(
                    title=title,filetypes=filetypes,initialdir=initialdir)
                return [theFile]
        else:
            # Return a single file name as a string.
            return tkFileDialog.askopenfilename(
                title=title,filetypes=filetypes,initialdir=initialdir)
Exemple #29
0
    def getData(self):
        """Read the data from txt files"""
        try:
            import matplotlib.pyplot as plt
            self.names = tkFileDialog.askopenfilenames(title='Choose acceleration files')
            self.num = 0
            for name in self.names:
                if(self.option == 0):
                    self.data = genfromtxt(name, delimiter=';')
                else:
                    self.data = genfromtxt(name, delimiter=',')
                self.lista.append(self.data)
                self.num = self.num + 1

            #Offset of each sample
            self.offsets =  zeros((1,self.num));
            self.limit_l = 0
            self.limit_r = 100
            self.off = tk.Scale(self.master, from_=-1000, to=1000, orient=tk.HORIZONTAL, resolution=1, length=600, command = self.setOffset, label = 'Offset')
            self.off.grid(row=7,column=0, columnspan = 5)
            self.ri = tk.Scale(self.master, from_=-800, to=800, orient=tk.HORIZONTAL, resolution=1, length=600, command = self.setLimit_r, label = 'Right limit')
            self.ri.set(self.limit_r)
            self.ri.grid(row=8,column=0, columnspan = 5)
            self.le = tk.Scale(self.master, from_=-1000, to=1000, orient=tk.HORIZONTAL, resolution=1, length=600, command = self.setLimit_l, label = 'Left limt')
            self.le.set(self.limit_l)
            self.le.grid(row=9,column=0, columnspan = 5)
            self.plotData("all")
            self.new_lista = self.lista
        except:
            showerror("Error in the files")
 def changeLbox(self, mytab):         
     root = gFunc.getRoot(mytab)
     mynewdata = tfgiag.askopenfilenames(parent=root,title='Choose a file',filetypes=[('CSV files', '.csv')])
     vals = []
     self.mainEventBox["values"] = vals
     if mynewdata:
         #reset old variables
         self.pb.start()
         self.data.maindata = pd.DataFrame()     
         self.lbox.delete(0, self.lbox.size())
         #populate lists and data
         for myfile in root.tk.splitlist(mynewdata): 
             foo = pd.read_csv(myfile, error_bad_lines=False)   
             if (self.data.maindata.empty):
                 self.data.setMainData(foo)
             else:
                 self.data.appendMainData(foo)
             eventlist = []
             for eventID in foo["Event ID"].unique():
                 self.lbox.insert(END, eventID)
                 eventlist.append(eventID)
                 vals.append(eventID)
             print myfile
         self.mainEventBox["values"] = vals
         self.mainEventBox.set(vals[0])
         self.pb.stop()
     else:
         print "Cancelled"
     return mynewdata
import Tkinter,tkFileDialog

root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
for file in filez:
# print root.tk.splitlist(filez)
        pupil15s_outname = pupil15s_outname.replace("-Delay", "-Recall")
        'Writing quartile data to {0}'.format(pupil15s_outname)
        pupildf15s.to_csv(pupil15s_outname, index=False)


if __name__ == '__main__':
    if len(sys.argv) == 1:
        print('')
        print('USAGE: {} <raw pupil file> '.format(
            os.path.basename(sys.argv[0])))
        print("""Processes single subject data from HVLT task and outputs csv
              files for use in further group analysis. Takes eye tracker data 
              text file (*.gazedata) as input. Removes artifacts, filters, and 
              calculates dilation per 1s.Also creates averages over 15s blocks."""
              )
        print('')
        root = tkinter.Tk()
        root.withdraw()
        # Select files to process
        filelist = filedialog.askopenfilenames(
            parent=root,
            title=
            'Choose HVLT recall-recognition pupil gazedata file to process')
        filelist = list(filelist)
        # Run script
        proc_subject(filelist)

    else:
        filelist = [os.path.abspath(f) for f in sys.argv[1:]]
        proc_subject(filelist)
Exemple #33
0
import numpy as np
import matplotlib.pyplot as plt
import pylab
import pandas as pd
import Tkinter, tkFileDialog

root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root,
                                      title='Choose 2 or more files',
                                      filetypes=(("csv files", "*csv"),
                                                 ("All files", "*.*")))
t = list(filez)
p = len(filez)
root.destroy()
print(p)
if p == 2:
    data0 = pd.read_csv(t[0], sep=u',', header=14, skip_footer=0)
    df0 = pd.DataFrame(data=data0, columns=['CH1', 'CH2', 'CH3', 'CH4'])

    data1 = pd.read_csv(t[1], sep=u',', header=14, skip_footer=0)
    df1 = pd.DataFrame(data=data1, columns=['CH1', 'CH2', 'CH3', 'CH4'])

    f, ax = plt.subplots(2, 2, figsize=(20, 10))
    ax[0, 0].plot(df0)
    ax.set_title("Title for second plot")
    ax[0, 1].plot(df1)
##################
elif p == 3:
    data0 = pd.read_csv(t[0], sep=u',', header=14, skip_footer=0)
    df0 = pd.DataFrame(data=data0, columns=['CH1', 'CH2', 'CH3', 'CH4'])
Exemple #34
0

if __name__ == '__main__':
    if len(sys.argv) == 1:
        print('')
        print('USAGE: {} <raw pupil file> '.format(
            os.path.basename(sys.argv[0])))
        print(
            """Takes eye tracker data text file (*.gazedata/*.xlsx/*.csv) as input.
              Uses filename and path of eye tracker data to additionally identify 
              and load eprime file (must already be converted from .edat to .csv. 
              Removes artifacts, filters, and calculates peristimulus dilation
              for congruent, incongruent, and the contrast between the two.
              Processes single subject data and outputs csv files for use in
              further group analysis.""")
        print('')
        root = tkinter.Tk()
        root.withdraw()
        # Select files to process
        filelist = filedialog.askopenfilenames(
            parent=root,
            title='Choose Stroop pupil gazedata file to process',
            filetypes=(("xlsx files", "*.xlsx"), ("all files", "*.*")))
        filelist = list(filelist)
        # Run script
        proc_subject(filelist)

    else:
        filelist = [os.path.abspath(f) for f in sys.argv[1:]]
        proc_subject(filelist)
Exemple #35
0
INSERT_GROUP_BY_COMMAND = """
    INSERT INTO {tbn}
    SELECT fips, year, month, day, hour, 
    count(*) total_tweets, count(CASE WHEN about_flood=1 THEN about_flood END) total_flood_tweets, 
    count(DISTINCT user_id) users 
    FROM tweets group by fips, year, month, day, hour
"""

if not os.path.exists(RESULTS_PATH): 
    os.makedirs(RESULTS_PATH)


if __name__== "__main__":
    try: 
        coastal_counties_tweets_db_files = fd.askopenfilenames(title="Choose coastal counties tweets databases")
        
        if not coastal_counties_tweets_db_files: 
            raise Exception('\nNo databases selected! Goodbye.\n')
    except Exception as e: 
        print e
        sys.exit()

    total_time = 0 

    for i, tweet_db_file in enumerate(coastal_counties_tweets_db_files): 
        print '{} out of {} databases'.format(i + 1, len(coastal_counties_tweets_db_files))

        start = time.time()

        current_tweet_db = Database(tweet_db_file)
Exemple #36
0
        # Create a new container

        conn.put_container(container_name)
        print "\nContainer %s created successfully." % container_name
    elif choice == 2:
        # List your containers
        print("\nContainer List:")
        for container in conn.get_account()[1]:
            print container['name']
    elif choice == 3:
        #create file
        root = Tkinter.Tk()
        root.withdraw()
        root.update()
        fa = tkFileDialog.askopenfilenames(parent=root,
                                           initialdir="/",
                                           title='Choose a file')
        size = 0
        for filenames in fa:
            #d=os.path.basename(filenames)
            size += os.path.getsize(filenames)
            #print root.tk.splitlist(d)
        #file_name=os.path.basename(fa)

        #size=os.stat(lst).stsize
        a = humanize.naturalsize(size)
        print('File created successfully')
        print(a)

        #open(file_name, 'w').write('Hello')
        #print ("File Created")
Exemple #37
0
 def OpenFile(self):
     self.app.grid_forget()
     level_files = self.app.tk.splitlist(askopenfilenames(initialdir=os.path.join(_ROOT, 'levels')))
     self.app.level_files = list(level_files)
     self.app.start_next_level()
Exemple #38
0
# 1. User select all .csv files that need to be cleaned
# 2. User input whether to remove sequences with stop codon (but not the amber stop)
# 3. User input whether to remove sequences with frame shift. If yes, then provide the correct last two  amino acids sequences
# 4. User input whether to map each sequence to its template (only Reflexion and CKP are considered here, but the list can be expanded)

import Tkinter
import tkFileDialog
import os
import pandas as pd

root6 = Tkinter.Tk(
)  # if you are using Canopy, please go to 'Preferences > Python > PyLab Backend: Inline(SVG)'
root6.withdraw()
root6.update()
file_paths = tkFileDialog.askopenfilenames(
    title=
    'Please select the COUNT files that need to be cleaned (multiple files ok)'
)
root6.destroy()
rmv_stop = raw_input("Remove sequences contain stop codon (Y or N): ")
rmv_fshift = raw_input("Remove frame-shift (Y or N): ")
if (rmv_fshift == 'Y') or (rmv_fshift == 'y'):
    fshift = raw_input(
        "Last two amino acids when there is no frame-shift (ex: SG for Relfx): "
    )
frm_search = raw_input("Map the framework (Y or N): ")
if (frm_search == 'Y') or (frm_search == 'y'):
    lib = raw_input("Please specify the library: Relexion = 1, CKP = 2 ")

for file_path in file_paths:
    file_name = os.path.basename(file_path).split('.')[0]
    test = pd.read_csv(file_path, header=0)
Exemple #39
0
#encoding=utf-8

#xlxs module
import openpyxl

# windows modules
import tkFileDialog
import tkMessageBox

import os

#Read the path of files Using tkfiledialog
source_filename = tkFileDialog.askopenfilenames(title='file',
                                                filetypes=[('excel',
                                                            '*.xls *.xlsx')])
if len(source_filename) == 0:
    print u'无文件被选择'
    exit()
filename_target = os.path.splitext(source_filename[0])[0] + '-Merge.xlsx'
print os.path.split(filename_target), os.listdir(
    os.path.split(filename_target)[0])
if os.path.split(filename_target)[1] in os.listdir(
        os.path.split(filename_target)[0]):
    print u'文件已存在!'
#    exit()

#Read data and Write data
file_write = openpyxl.Workbook()
file_write.save(filename_target)
w1 = openpyxl.load_workbook(filename_target)
Sheet_target = w1[w1.sheetnames[0]]
Exemple #40
0
 def open_files(self):
     self.file_names = askopenfilenames()
     self.file_entry_p1.clear()
     self.file_entry_p1.insert(0, self.file_names)
def openfile():
    filenames = askopenfilenames(filetypes=(('data files', '*.PRN'),
                                            ('all files', '*.*')),
                                 initialdir="/home/nelson/Documents/lab/",
                                 parent=Tk())
    return filenames
Exemple #42
0
    def V_analisis(self):
        "Parametro=0"
        self.nombres = []
        self.Value = {}
        self.Operaciones = {}
        self.CiclosDeReloj = {}
        self.OperacionesTotales = []
        Cuidado = 0
        Barrera = 0
        self.AnalisisP = 0
        self.NombreP = []
        ArchivosCorrectos = 0
        self.nombres = tkFileDialog.askopenfilenames(
            initialdir="/",
            title="Select file",
            filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*")))
        for comprobacion in self.nombres:
            "Barrabaja=0"

            cerrado = 0
            parametro = 0
            for c in range(comprobacion.__len__()):
                if comprobacion[comprobacion.__len__() - c -
                                1] == "_" and Cuidado < 2 and cerrado < 1:
                    Cuidado = Cuidado + 1
                if comprobacion[comprobacion.__len__() - c - 1] == "/":
                    cerrado = 1
                if Cuidado == 1 and comprobacion[comprobacion.__len__() - c -
                                                 1] == "P":
                    parametro = 1

            self.NombreP.append(comprobacion[comprobacion.__len__() - 1])

            if parametro != 1 or Cuidado != 2:
                Barrera = 1

            if comprobacion[len(comprobacion) - 1] != "y" or comprobacion[
                    len(comprobacion) - 2] != "p" and self.comprobacion[
                        len(comprobacion) - 3] != ".":
                ArchivosCorrectos = 1

        if ArchivosCorrectos == 1:
            tkMessageBox.showerror(
                "Error", "El fichero seleccionado no es de tipo .py")
        elif self.nombres.__len__() == 1:
            tkMessageBox.showerror("Error", "Solo has seleccionado 1 fichero")
        elif self.nombres.__len__() == 0:
            tkMessageBox.showwarning()("Error",
                                       "No se ha seleccionado ningun fichero")
        else:
            if self.nombres.__len__() <= 10:
                if self.Boton1 == 0:
                    if self.Boton2 == 1:
                        self.btn3.pack_forget()
                    self.btn3 = Tkinter.Button(self,
                                               text="Comparison of files",
                                               command=lambda: self.pasa.
                                               show_frame(VentanaComparacion))

                    self.btn3.pack()
                    self.Boton1 = 1
                    self.Boton2 = 0
            else:
                if self.Boton2 == 0:
                    if self.Boton1 == 1:
                        self.btn3.pack_forget()
                    self.btn3 = Tkinter.Button(self,
                                               text="Comparison of files",
                                               command=lambda: self.pasa.
                                               show_frame(VentanaComparacion2))

                    self.btn3.pack()
                    self.Boton1 = 0
                    self.Boton2 = 1

                if Barrera == 0:
                    self.AnalisisP = 1

            Checkbutto = []
            Unidades = []
            posi = 190
            enumera = 1

            for ficherin in self.nombres:
                lab = []
                CiclosDeReloj_dentro = {}
                f = open(ficherin, 'r')
                mensaje = f.read()

                CAPTURE_EXCEPTION = 1

                code = mensaje
                f.close()

                code = textwrap.dedent(code)
                code = compile(code, "<%s>" % id(code), "exec", 0, 1)
                dis_code(code)
                vm_stdout = six.StringIO()
                vm = VirtualMachine()
                vm_value = self.vm_exc = None
                vm_value = vm.run_code(code)

                for i in vm.opera.keys():
                    lab.append(i[0] + "_" + str(i[1])[7:10] + "_" +
                               str(i[2])[7:10])

                labels = lab
                self.Operaciones[enumera] = lab
                "self.OperacionesF=lab"
                self.Value[enumera] = vm.opera.values()
                "self.ValoresF=vm.opera.values()"
                for oper in lab:
                    if oper not in self.OperacionesTotales:
                        self.OperacionesTotales.append(oper)

                for archivo in Procesadores.Archivos_csv:
                    Unidades = self.SacarCiclosDeReloj(archivo,
                                                       vm.opera.keys())
                    aux = []
                    cont = 0
                    for a in self.Value[enumera]:
                        aux.append(a * int(Unidades[cont]))
                        cont += 1

                    CiclosDeReloj_dentro[archivo] = aux
                self.CiclosDeReloj[enumera] = CiclosDeReloj_dentro
                enumera = enumera + 1
            app.frames[VentanaComparacion].Comba[
                "values"] = self.OperacionesTotales
            app.frames[VentanaComparacion2].Comba[
                "values"] = self.OperacionesTotales

            tkMessageBox.showinfo("Exito", "El analisis ya ha sido realizado")
            "app.frames[VentanaComparacion].Comba.pack()"
            app.frames[VentanaComparacion].btn2.pack()
            "app.frames[VentanaComparacion2].Comba.pack()"
            app.frames[VentanaComparacion2].btn2.pack()
            "app.frames[VentanaComparacion].Muestra_Botones()"
            "app.frames[VentanaComparacion2].Muestra_Botones()"
            app.frames[VentanaOperaciones].Muestra_Operaciones()
            app.frames[VentanaOperaciones3].Muestra_Operaciones()

            for marcar in range(
                    0, app.frames[VentanaOperaciones].VBoton.__len__()):
                "app.frames[VentanaComparacion].Checkbutto[marcar].invoke()"
                "app.frames[VentanaComparacion2].Checkbutto[marcar].invoke()"
                app.frames[VentanaOperaciones].Checkbutto[marcar].invoke()
                app.frames[VentanaOperaciones3].Checkbutto[marcar].invoke()
Exemple #43
0
def LoadFiles(parent=None, title=None, initialdir=os.curdir, **args):
    result = tkFileDialog.askopenfilenames(parent=parent, title=title, initialdir=initialdir, **args)
    if not result: result = None
    else: result=str(result)
    return result
Exemple #44
0
 def select_files(self):
     f = tkFileDialog.askopenfilenames(**self.file_opt)
     #if user clicked cancel, we won't remove previously chosen files
     if len(f) > 0:
         self.selected_files = f
         self.file_display.display()
Exemple #45
0
 def _add_files(self):
     filepaths = filedialog.askopenfilenames(initialdir='~/', filetypes=(
         ('Lib File', '*.lib'), ('Frcmod File', '*.frcmod'), ('Xml File', '*.xml')))
     for filepath in filepaths:
         self.ui_files_to_load.insert('end', filepath)
Exemple #46
0
    os.startfile(Nexus_Path)
    root.lift()
    root.wm_attributes("-topmost", 1)
    tkMessageBox.showinfo('Info', 'Click OK when Nexus has opened')
    vicon = ViconNexus.ViconNexus()

#Select patient data. any number of valid c3d files can be opened

root.lift()
root.wm_attributes("-topmost", 1)

# ********Change 'intialdir = ...' as required ********
trials = tkFileDialog.askopenfilenames(
    parent=root,
    initialdir=
    "\\\\rjah\\dfs\\orlau-clinical\\clinical\\Vicon 612\\Network Clinical",
    filetypes=[("c3d File", "*.c3d")],
    title="Gait Profile Score: Select Trial Data")

#Select control data. Must be in a csv file, with kinematic variables in columns, and normal means & SDs in final 2 columns

# ********Change 'intialdir = ...' as required ********
controlfile = tkFileDialog.askopenfilename(
    parent=root,
    initialdir="\\\\rjah\\dfs\\orlau-clinical\\clinical\\GPS\\Control Data",
    filetypes=[("csv File", "*.csv")],
    title="Gait Profile Score: Select Control Data")

#Read and format control data
temp_data = np.genfromtxt(controlfile, delimiter=',')
Exemple #47
0
                uid=user_id))
        for location in db.cursor:
            user_locations.add(location[0])
    db.connection.close()
    return user_locations


if __name__ == "__main__":
    users = [
        265190144, 388459151, 2407950806L, 29379629, 2329340188L, 60829975,
        2153231840L, 179451754, 2243507567L, 501358792, 383577929, 1717302079,
        2206188373L, 2261728016L, 245644335, 2148204210L, 1112495810,
        207530211, 407762380, 971330550
    ]

    dbs = fd.askopenfilenames(title='Get databases')

    s = time.time()

    pool = mp.Pool(processes=mp.cpu_count())

    processes = [
        pool.apply_async(get_user_locations, args=(uid, dbs)) for uid in users
    ]

    # for uid in users:
    #     print get_user_locations(uid, dbs)

    for p in processes:
        print p.get()
Exemple #48
0
import os
from mutagen.mp3 import MP3
from Tkinter import Tk
from tkFileDialog import askopenfilenames

Tk().withdraw(
)  # we don't want a full GUI, so keep the root window from appearing
files_list = askopenfilenames(
)  # show an "Open" dialog box and return the path to the selected file

for f in files_list:
    if ".mp3" in f:
        path = f[0:f.rfind('/') + 1]
        file_name = f[f.rfind('/') + 1:]
        audio = MP3(f)
        new_name = path + str(
            audio.info.length // 60)[:-2] + 'minutes-' + file_name
        os.rename(f, new_name)
Exemple #49
0
from utils.separation import chunkify
from utils.database import Database

from utils.timing import str2date
from math import ceil

import tkFileDialog as fd
import multiprocessing as mp
import time
import sys, os

NCHUNKS_FIPS = 100

if __name__ == '__main__':
    try:
        tweet_stats_db_file = fd.askopenfilenames(
            title='Choose database with tweet statistics')

        if not tweet_stats_db_file:
            raise Exception('\nNo database selected! Goodbye.\n')
    except Exception as e:
        print e
        sys.exit()

    s = time.time()

    tweet_stats_db = Database(tweet_stats_db_file)

    unique_fips = sorted([
        str(fips[0]).zfill(5) for fips in tweet_stats_db.select(
            'SELECT DISTINCT fips FROM statistics')
    ])
Exemple #50
0
        pool.apply_async(save_unique_users_per_db, args=(db_file, ))
        for db_file in db_files
    ]

    for p in processes:
        p.get()


def raw_users_insert(db_files):
    for db_file in db_files:
        save_unique_users_per_db(db_file)


if __name__ == "__main__":
    try:
        dbs = fd.askopenfilenames(title='Get databases')[:TEST_SIZE]

        if not dbs:
            raise Exception('\nNo databases selected! Goodbye.\n')
    except Exception as e:
        print e
        sys.exit()

    s = time.time()

    if METHOD:
        parallel_users_insert(dbs)
    else:
        raw_users_insert(dbs)

    print '\nElapsed Time: {}s\n'.format(round(time.time() - s, 2))
Exemple #51
0

def parallel_importing(chunks, factor=1):
    pool = mp.Pool(processes=mp.cpu_count() * factor)

    processes = [
        pool.apply_async(commit_chunk, args=(chunk, )) for chunk in chunks
    ]

    for p in processes:
        p.get()


if __name__ == '__main__':
    try:
        files = fd.askopenfilenames(title='Choose tweet files to import')
        # files = [os.path.join(wd, f) for f in os.listdir(wd)][:TEST_SIZE]
        chunks = [files]  # chunk_files_by_day(files)
    except Exception as e:
        print '\nNo directory selected! Goodbye.\n'
        sys.exit()

    s = time.time()

    if METHOD:
        parallel_importing(chunks)
    else:
        raw_importing(chunks)

    print '\nElapsed Time: {}s\n'.format(round(time.time() - s, 2))
    print 'Method: {}, Size: {}\n'.format(METHOD_STR, TEST_SIZE)
Exemple #52
0
 def OnLoad(self):
     fileNames = askopenfilenames(filetypes=[('Split Files', '*')])
     for f in fileNames:
         print f
Exemple #53
0
 def SelectInputFiles(self, *args):
     filenames = tkFileDialog.askopenfilenames()
     if filenames:
         self.input_filenames = filenames
rot = 45


#Define functions & secondary variables
def numRemover(feat):
    if isinstance(
            feat,
            basestring) == 1:  #Temp fix to bypass nan in edited .csv files
        trimmed = feat.split('(')
        return trimmed[0]


#Ask user to select excel files. Store file paths in fileList
root = tk.Tk()
root.withdraw()
filePathList = tkFileDialog.askopenfilenames(parent=root,
                                             title='Choose .csv files')

#Declare lists to store info data about each file. range is the number of variables
numLarv, col, fileNameExt, fileName, x, y, v, v_avg, dst, org, bend, go, go_avg, left, left_avg, right, right_avg, coil, coil_avg = (
    [0] * len(filePathList) for i in range(19))

#Get directory of files
dir = os.path.dirname(filePathList[0])

#Create list of file names from the full file paths
for i in range(0, len(filePathList)):
    fileNameExt[i] = os.path.basename(
        filePathList[i])  #Extract file name w/ extension
    fileName[i] = os.path.splitext(fileNameExt[i])[0]  #Remove extension
    # print fileName[i]
Exemple #55
0
'''genfromttxt(skip 32 headers, plot from data)
    
    open file names in array then loop...
    
    len(linspace) linspace = file ##
    data = [n, m]
    
    plotdata(data[:, 0], data[:, 1], loop#)'''

ftypes=[
        ('csv', '*.csv'),
        ('All files', '*')
        ]

root = Tkinter.Tk()
files = tkFileDialog.askopenfilenames(parent=root,title='Choose a file',filetypes=ftypes)
#files=string2Temp.string2Temp(files,'MoOx_DHS_34nm_')
print files

for i in range (0, len(files)):
    angle=[]
    int=[]
    angle,int = np.loadtxt(files[i], skiprows=33, dtype=None, delimiter=",",unpack=True)
    file=files[i].split('/')[-1]
    plt.semilogy(angle,int,label = file.strip('.csv'), alpha=0.5)



plt.xlabel(r'Angle(Degrees)')
plt.ylabel('Intensity')
plt.legend(fontsize=10)
import tkMessageBox
from Tkinter import *

import zipfile
from os.path import basename
import pandas as pd

root = Tk()

# Reading zip files
base_zip = tkFileDialog.askopenfilename(initialdir="/",
                                        title="Select Base ubx zip file",
                                        filetypes=(("zip files", "*.zip"),
                                                   ("all files", "*.*")))
rover_zip = tkFileDialog.askopenfilenames(initialdir="/",
                                          title="Select Rover ubx files",
                                          filetypes=(("zip files", "*.zip"),
                                                     ("all files", "*.*")))

# Asking for Position of Base
base_pos_prompt = booldialogbox("Do you want enter position of base?")

if base_pos_prompt == 1:  # Taking Base coordinates, then enter csv else continue
    base_pos = tkFileDialog.askopenfilename(initialdir="/",
                                            title="Select Position csv files",
                                            filetypes=(("csv file", "*.csv"),
                                                       ("all files", "*.*")))

    # Reading csv as pandas dataframe and then numpy array
    # Lat, Long, Ele
    csv_pos = pd.read_csv(base_pos)
    csv_matrix = csv_pos.values
                                                    'Wang Lab')
        if not os.path.exists(os.path.dirname(intermed_outname)):
            os.makedirs(os.path.dirname(intermed_outname))
        dfresamp1s['Timestamp'] = dfresamp1s.Timestamp.dt.strftime('%H:%M:%S')
        dfresamp1s.to_csv(intermed_outname, index=False)


if __name__ == '__main__':
    if len(sys.argv) == 1:
        print('')
        print('USAGE: {} <raw pupil file> '.format(
            os.path.basename(sys.argv[0])))
        print("""Processes single subject data from digit span task and outputs
              csv files for use in further group analysis. Takes eye tracker 
              data text file (*.gazedata) as input. Removes artifacts, filters, 
              and calculates dilation per 1sec.""")
        root = tkinter.Tk()
        root.withdraw()
        # Select files to process
        filelist = filedialog.askopenfilenames(
            parent=root,
            title='Choose Digit Span pupil gazedata file to process')
        filelist = list(filelist)

        # Run script
        proc_subject(filelist)

    else:
        filelist = [os.path.abspath(f) for f in sys.argv[1:]]
        proc_subject(filelist)
Exemple #58
0
        
    print('docbuild ran in %s' %pdf_path)
    doc.build(story)
    
if __name__ == "__main__":    
    
    trials = list()
    class Trial(object):
        def __init__(self, datalist):
            self.allchannels = datalist[0]
            self.allemg = datalist[1]
            self.patientname = datalist[2]
            self.strikes = datalist[3]
            self.footoff = datalist[4]
            self.start_end = datalist[5]
    
    trialnames = tkFileDialog.askopenfilenames(initialdir= "C:",
                           filetypes =[("c3d File", "*.c3d")],
                           title = "Select Trial Data")

    for trial in trialnames:                     
        trials.append(Trial(pull_trial(str(trial))))
    
    print('strikes & footoff below')    
    print(trials[0].strikes)
    print(trials[0].footoff)
    app = App(root, trials)
    root.mainloop()
    for n in range(len(trialnames)):
        os.remove(str('emg-plot-'+str(n)+'.png'))
    print('cleanup complete')
Exemple #59
0
# Opens a .wav file(s) and extracts spectral information, aggregates to file
import essentia
from essentia.standard import *
from heightmap import getFrames
from pprint import pprint
import Tkinter as tk
import tkFileDialog
import simplejson as json

## Open dialog for user to select files
root = tk.Tk()
root.withdraw()
fileNames = tkFileDialog.askopenfilenames()

#Create an array of audio signals, use Essentia loader to use with Extractor()
## Add audio to array
loadedAudioFiles = []

for fileName in fileNames:
    loader = MonoLoader(filename=fileName)
    loadedAudioFiles.append(loader())

##Create arrays for analysis data and load essentia analysis algorithm Extractor()
dataPools = []
dataPoolsAggregated = []
specFrames = []
specFramesAggregated = []
extractor = Extractor()

## Here we get the raw analysis data and spectra (from heightmap.py), as well as a supplementary aggregated file
## aggregated files will allow for easier implementation of system constraints later on, following analysis of test inputs
Exemple #60
0
import tkFileDialog as fd
import time, sys, os
import multiprocessing as mp

RESULTS_PATH = os.path.join(os.getcwd(), 'results')

if not os.path.exists(RESULTS_PATH):
    os.makedirs(RESULTS_PATH)

CURRENT_COUNTIES_TABLE = 'counties'

if __name__ == "__main__":
    try:
        coastal_counties_db_file = fd.askopenfilename(
            title="Choose coastal counties database")
        tweet_db_files = fd.askopenfilenames(
            title="Choose ALL databases with tweets")

        if not coastal_counties_db_file or not tweet_db_files:
            raise Exception('\nNo databases selected! Goodbye.\n')
    except Exception as e:
        print e
        sys.exit()

    coastal_counties_db = Database(coastal_counties_db_file)

    for i, tweet_db_file in enumerate(tweet_db_files):
        print '{} out of {} databases'.format(i + 1, len(tweet_db_files))

        current_coastal_counties_db_file = os.path.join(
            RESULTS_PATH,
            os.path.split(tweet_db_file)[1])