예제 #1
0
def printBT():
    lblprintBTN.config(text="Working!")
    files = filedialog.askopenfiles()
    p = str(files[0].name).replace("/", "\\").rsplit('\\', 1)[0]
    os.chdir(p)
    for x in files:
        path = str(x.name).replace("/", "\\")
        print(path)
        with Pdf.open(path) as pd:
            length = len(pd.pages)
            name = path.split("\\")[-1]

            pdsplit = []
            pdsplit2 = []
            for n, page in enumerate(pd.pages):
                if n % 2 == 0:
                    pdsplit.append(page)
                else:
                    pdsplit2.append(page)
            i = 0
            pdfsplit1 = Pdf.new()
            pdfsplit2 = Pdf.new()
            for n, x in enumerate(pdsplit):
                pdfsplit1.pages.append(x)

            for n, x in enumerate(pdsplit2):
                pdfsplit2.pages.append(x)

            pdfsplit1.save(name.replace(".pdf", "xSplit1.pdf"))
            pdfsplit2.save(name.replace(".pdf", "xSplit2.pdf"))
    lblprintBTN.config(text="Done!")
예제 #2
0
 def join_data(self):
     fl = askopenfiles()
     if fl:
         tdatas = []
         cols = 0
         lrows = []
         for f in fl:
             res = self.parse(f.read())
             f.close()
             tdatas.append(res['tdata'])
             cols += res['cols']
             lrows.append(res['rows'])
         rows = min(lrows)
         self.init(cols, rows)
         col = 0
         for tdata in tdatas:
             for lcol in tdata:
                 row = 0
                 for sbyte in lcol:
                     sbyte = ('0' * (8 - len(sbyte))) + sbyte
                     if len(sbyte) != 8:
                         raise Exception('Supported only byte arrays.')
                     for b in sbyte:
                         self.data[col][row] = int(b)
                         row += 1
                 col += 1
         self.update()
    def _callback_button_load_cnv_files(self, *args, **kwargs):
        file_objects = filedialog.askopenfiles(
            title='Select files',
            initialdir=str(
                Path(
                    self.user.directory.setdefault(
                        'cnv_files',
                        r'\\winfs-proj\proj\havgem\EXPRAPP\Exprap2020'))),
            filetypes=[('cnv-files', '.cnv')])
        if not file_objects:
            return

        self.cnv_files_paths = {}
        directory = ''
        items = []
        for item in file_objects:
            file_path = Path(item.name)
            file_name = file_path.name
            directory = file_path.parent
            items.append(file_name)
            self.cnv_files_paths[file_name] = file_path

        self.user.directory.set('cnv_files', str(directory))

        self.strvar_cnv_directory.set(directory)
        self.cnv_files_selection_widget.update_items(items)
        self.cnv_files_selection_widget.move_items_to_selected(items)
        self.logger.info('CNV files loaded')
예제 #4
0
def add_file():
    choice = filedialog.askopenfiles()
    
    with open(app_paths) as f:
        for row in f:
            print(row.replace('\n', '').split(' -> '))
    return
예제 #5
0
def dizinSec():
    file_path_string = filedialog.askopenfiles()

    yol = str(file_path_string)

    print(yol)

    global liste, liste2
    liste = []
    liste2 = []

    for i in yol.split():
        liste.append(i)
    print(liste[1])

    for i in liste[1].split('='):
        liste2.append(i)
    print(liste2[1])

    kelime1 = esasKelime.get()
    kelime2 = sonHali.get()

    global kelime3, yedek, sil, yarat

    # kelime3 = "'sed '" + "'s/'" + kelime1 + "'/'" + kelime2 + "'/g'" + "' '" + liste2[1]
    yedek = "/home/aspa/Desktop/yedek.txt"
    kelime3 = 'sed ' + "'" + 's/' + kelime1 + '/' + kelime2 + '/g' + "'" + ' ' + liste2[
        1] + ' >' + yedek
    sil = 'rm ' + liste2[1]
    yarat = 'mv ' + yedek + ' ' + liste2[1]
예제 #6
0
def getAskOpenFiles():
    # 複数ファイル選択するためのdialogになります。
    # read only
    # 戻り値 : Openを選択してファイルを開いた場合 : [ファイル情報1, ファイル情報2, ...], Cancelを選択した場合 : ''
    fileData = filedialog.askopenfiles()
    # レスポンスの内容を表示する。
    print("ask open files", fileData)
예제 #7
0
    def askopenfile(self):
            self.file_opt = options = {}
            options['initialdir'] = 'C:\\'
            options['parent'] = root
            options['title'] = 'This is a title'
            """Returns an opened file in read mode."""
            usame = filedialog.askopenfiles(filetypes = (("Excel files", "*.xls;*.xlsx"),("All files", ".*")))

            datas={}

            for files in usame:
                result ={}
                dosya = files.name
                fileName = basename(dosya)
                rows = []
                wb = open_workbook(dosya)
                sh = wb.sheet_by_index(0)
                for rownum in range(sh.nrows):
                    rows.append(sh.row_values(rownum))
                rows.__delitem__(0)

                courseDatas={}
                for itemDatas in rows:
                    courseName = itemDatas[0]+" "+itemDatas[1]
                    courseGrade = itemDatas[2]
                    courseDatas[courseName]= courseGrade
                datas[fileName] = courseDatas
예제 #8
0
def askOpenFiles(**kw):
	files = filedialog.askopenfiles(**kw)
	try:
		yield files
	finally:
		for file in files:
			file.close()
        def reading_data(namedirection):

            opened_csv_files = fd.askopenfiles(title=namedirection,
                                               filetypes=[
                                                   ('CSV files', '*.csv'),
                                               ],
                                               initialdir='')

            start_read = time.time()

            #определение номера канала из названия файла
            name_ch = str(opened_csv_files)
            name_temp = name_ch = name_ch.split('/')
            if int(name_ch[len(name_ch) - 1][3]) == 1:
                name_ch = '1 канал'
            else:
                name_ch = '2 канал'

            # определение номера ТГ из названия файла
            name_TG = int(name_temp[len(name_temp) - 1][2])

            list_ = []
            for file_ in opened_csv_files:
                df = pd.read_csv(file_,
                                 header=0,
                                 delimiter=';',
                                 usecols=fields)
                list_.append(df)
            data_out = pd.concat(list_)
            time_read = '%.2f' % float(time.time() - start_read)

            return data_out, time_read, name_TG
예제 #10
0
def askOpenFiles(**kw):
    files = filedialog.askopenfiles(**kw)
    try:
        yield files
    finally:
        for file in files:
            file.close()
예제 #11
0
 def __init__(self, file_paths_org, x=None, y=None):
     '''
   allow user to load pdf files
   alter file_paths
   '''
     self.x = x
     self.y = y
     file_paths = file_paths_org
     files = filedialog.askopenfiles(initialdir="/",
                                     title="Select files",
                                     filetypes=(("PDF Files", "*.pdf"), ))
     for file in files:
         # don't allow duplicate file paths
         if file.name not in file_paths:
             file_paths.append(file.name)
     # check for bad files and remove them
     bad_files = []
     fc = FileChecker()
     for x in range(len(file_paths)):
         if fc.isGood(file_paths[x]) == False:
             bad_files.append(file_paths[x])
     bad_files.reverse()
     for bad_file in bad_files:
         if bad_file in file_paths:
             file_paths.remove(bad_file)
     if len(bad_files) > 0:
         self.showBadFiles(bad_files)
예제 #12
0
def main(args=None):
    # Open a file selection dialog, restrict to CSV extensions
    csv_file_streams = filedialog.askopenfiles(filetypes=[('CSV files', '.csv'), ('All files', '*')])

    pipeline_outputs = flatten([
        transformation_pipeline(
            csv_file_stream, 
            PitotMeasureModel(
                z=get_altitude_from_filename(csv_file_stream.name),
                a_ref=A_REF,
                a_z=A_Z,
                rho=RHO,
                k_ref=K_REF,
                k_z=K_Z
            )
        )
        for csv_file_stream in csv_file_streams])

    # Exploit result, create csv result file
    output_file = filedialog.asksaveasfilename(
        filetypes=[('CSV files', '.csv'), ('All files', '*')],
        defaultextension='.csv')
    with open(output_file, "w", newline="") as result_file:
        result_writer = csv.writer(result_file)
        result_writer.writerow(list(pipeline_outputs[0]._fields))
        for row in pipeline_outputs:
            result_writer.writerow(list(row))
    def add_evidence(self):
        """
        Allows the user to select one or more files to upload as evidence for a section.
        These files are then added to the resource table and displayed in a list
        within the section's associated page. If the upload is successful, the student
        is returned to the overview page.
        """
        # if section time is complete, evidence can now be uploaded
        planned_end_date = datetime_logic.calculate_end_date(
            int(self.section_obj.activity_timescale),
            self.section_obj.activity_start_date)
        if not datetime_logic.date_in_past(planned_end_date):
            msg.showwarning(
                'File upload',
                f'You cannot upload evidence until you have reached the '
                f"section's end date ({datetime_logic.datetime_to_str(planned_end_date)})."
            )
        else:
            # opens a file selection dialog in the user's home directory
            # the user can select as many files as they wish
            selected_files = filedialog.askopenfiles(
                title='Please select file(s) to add as evidence.',
                initialdir=os.path.expanduser('~'))

            num_files_uploaded = self.resource_table.add_student_resources(
                selected_files, self.student.student_id,
                self.section_obj.section_id)

            if num_files_uploaded > 0:
                msg.showinfo(
                    'File upload',
                    f'{num_files_uploaded} file(s) uploaded successfully.')
                self.page_back()
            else:
                msg.showinfo('File upload', 'No file(s) selected to upload.')
예제 #14
0
 def show_delete(self):
     """
     Show a dialog to preview and delete files.
     TODO: Replace 'Open' label on button with delete.
     TODO: Show title on dialog.  filedialog rot?
     TODO: Limit to image types under selected directory.
     """
     files = filedialog.askopenfiles(initialdir=self.directory,
                                     parent=self.root,
                                     mode='rb',
                                     title='Select files to delete...')
     if files:
         logging.debug('lock delete')
         self.lock.acquire()
         for file in files:
             file_name = file.name
             logging.info('deleting {}'.format(file_name))
             try:
                 os.remove(file_name)
             except OSError as ose:
                 logging.error('cannot delete {}: {}'.format(
                     file_name, ose))
         self.display_next()
         self.lock.release()
         logging.debug('release delete')
    def reading_data(namedirection):
        opened_csv_files = fd.askopenfiles(title=namedirection, filetypes=[('CSV files', '*.csv'), ], initialdir='')

        data_out = pd.DataFrame()
        list_ = []
        temp_time_2 = []
        start_read = time.time()
        for file_ in opened_csv_files:
            df = pd.read_csv(file_, header=0, delimiter=';', usecols=fields)
            list_.append(df)
        data_out = pd.concat(list_)
        temp_time = df[time_column]
        i = 0
        summa = 0
        while i < len(df[time_column]) - 1:
            if (df[time_column][i + 1] - df[time_column][i]) != -990:
                summa = summa + (df[time_column][i + 1] - df[time_column][i]) / 1000
                temp_time_2.append('%.2f' % summa)
            else:
                summa = summa + (1 + (df[time_column][i + 1] - df[time_column][i]) / 1000)
                temp_time_2.append('%.2f' % summa)
            i = i + 1
        temp_time_2.append(temp_time_2[len(temp_time_2) - 1])

        print('массив ВРЕМЯ cформирован')

        # data_out = pd.concat(temp_time_2)

        print(time.time()-start_read)

        # print(data_out.head)
        # print(len(temp_time_2))

        return data_out, temp_time_2, name_TG
예제 #16
0
파일: TeMail.py 프로젝트: k8scat/TeMail
 def choose_attachments(self):
     self.attachments = filedialog.askopenfiles(title='添加邮件附件')
     files = ''
     for i, attachment in enumerate(self.attachments):
         files += attachment.name
         if i != len(self.attachments) - 1:
             files += ';'
     self.mail_attach_in.set(files)
예제 #17
0
def img_add():
    global f_cnt, f_path_list
    f_conf = [("Text Files", ("jpg", "png", "jpeg"))]
    paths = tkfd.askopenfiles(filetypes=f_conf)
    for f in paths:
        imgList.insert("", "end", values=(len(f_path_list), f.name))
        f_path_list.append(f.name)
    msgList.insert(0, "画像を{0}件追加しました".format(len(paths)))
예제 #18
0
def getSources():
    # get the files you want
    filenames = filedialog.askopenfiles(parent=root,
                                        mode='r',
                                        title="Choose source files")
    for f in filenames:
        listbox.insert(tkinter.END, f.name)
        filelist.append(f.name)
예제 #19
0
 def open_files(self):
     # 调用askopenfile方法获取多个打开的文件
     print(
         filedialog.askopenfiles(
             title='打开多个文件',
             filetypes=[("文本文件", "*.txt"),
                        ('Python源文件', '*.py')],  # 只处理的文件类型
             initialdir='g:/'))  # 初始目录
예제 #20
0
def add_file():
    files = filedialog.askopenfiles(
        title="Select Images",
        filetypes=(("PNG File", "*.png"), ("All File", "*.*")),
        # Raw Srtring
        initialdir=r"/Users/macbookair/Desktop/python/")
    for file in files:
        list_file.insert(END, file.name)
예제 #21
0
def choose_files(title=None):
    """
    Returns a list containing io wrapper objects pointing towards the selected files in the system.
    """
    _setup_root()
    files = []
    files.append(filedialog.askopenfiles(title=title))
    return files
예제 #22
0
def loader():
    Data = filedialog.askopenfiles(
        mode='r',
        initialdir=
        "\Test_multifile_script\logical topography grapher object\data")
    x = Data[0]
    b = x.read()
    print(b)
        def reading_data(namedirection):

            opened_csv_files = fd.askopenfiles(title=namedirection,
                                               filetypes=[
                                                   ('CSV files', '*.csv'),
                                               ],
                                               initialdir='')

            #определение номера канала из названия файла
            name_ch = str(opened_csv_files)
            name_temp = name_ch = name_ch.split('/')
            if int(name_ch[len(name_ch) - 1][3]) == 1:
                name_ch = '1 канал'
            else:
                name_ch = '2 канал'

            # определение номера ТГ из названия файла
            name_TG = int(name_temp[len(name_temp) - 1][2])

            data_out = pd.DataFrame()
            list_ = []
            temp_time_2 = []
            start_read = time.time()
            for file_ in opened_csv_files:
                df = pd.read_csv(file_,
                                 header=0,
                                 delimiter=';',
                                 usecols=fields)
                list_.append(df)
            data_out = pd.concat(list_)

            temp_time = df[time_column]

            i = 0
            summa = 0
            while i < len(df[time_column]) - 1:
                if (df[time_column][i + 1] - df[time_column][i]) != -990:
                    summa = summa + (df[time_column][i + 1] -
                                     df[time_column][i]) / 1000
                    temp_time_2.append('%.2f' % summa)
                else:
                    summa = summa + (
                        1 +
                        (df[time_column][i + 1] - df[time_column][i]) / 1000)
                    temp_time_2.append('%.2f' % summa)
                i = i + 1
            temp_time_2.append(temp_time_2[len(temp_time_2) - 1])

            print('массив ВРЕМЯ cформирован')

            # data_out = pd.concat(temp_time_2)

            print(time.time() - start_read)

            # print(data_out.head)
            # print(len(temp_time_2))

            return data_out, temp_time_2, name_ch, name_TG
예제 #24
0
    def Importar(self, modo, auto=False, ruta=""):
        ## Leera la entrada y lo pasará una lista con las rutas absolutas
        if modo == "carpeta":
            if (auto):
                self.rutaCarpeta = ruta
            else:
                self.rutaCarpeta = filed.askdirectory()
            print("Carpeta a importar", self.rutaCarpeta)
            if (self.rutaCarpeta != ""):
                mods = os.listdir(self.rutaCarpeta)
                self.Listar(self.rutaCarpeta, mods)

                #mbox.showerror(f"ERROR {sys.exc_info()[0].__name__}",sys.exc_info()[1])

        if modo == "file":
            self.archivosRaw = filed.askopenfiles(filetypes=[("Minecraft Mod",
                                                              "*.jar")])
            if (self.archivosRaw != ""):
                self.rutasArchivos = [x.name for x in self.archivosRaw]
                print("Archivos a importar:")
                for mod in self.rutasArchivos:
                    print(mod)
                print()

                self.rutaCarpeta = ""
                self.Listar(self.rutasArchivos)

        if modo == "zip":

            self.rutaArchivo = filed.askopenfile(
                filetypes=[("Archivo Zip",
                            "*.zip")]).name  #,("Archivo Rar","*.rar")
            print("Zip a descomprimir", self.rutaArchivo)
            if self.rutaArchivo != "":
                path = ""
                if (self.OS == "Windows"):
                    path = f"C:/Users/{os.getlogin()}/Appdata/Local/temp"
                elif (self.OS == "Linux"):
                    path = f"/home/{os.environ['USER']}/.cache"

                try:
                    os.mkdir(f"{path}/mods/")
                except:
                    pass
                miZip = zipf.ZipFile(self.rutaArchivo)
                print(f"{path}/mods/")
                miZip.extractall(f"{path}/mods/", pwd=None)
                miZip.close()
                print("OK descompresion")

                print("Ok todo\n")

                self.rutaCarpeta = f"{path}/mods/"
                print("DEBUG", os.listdir(self.rutaCarpeta))
                self.Listar(self.rutaCarpeta, os.listdir(f"{path}/mods/"))

        self.ActualizarLista()
예제 #25
0
 def img_add(self):
     f_conf = [('Text Files',
                ('.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.tif',
                 '.TIF', '.tiff', '.TIFF', '.bmp', '.BMP', '.pdf', '.PDF'))]
     paths = tkfd.askopenfiles(filetypes=f_conf)
     for f in paths:
         self.imgList.insert('',
                             'end',
                             values=(len(self.f_path_list), f.name))
         self.f_path_list.append(f.name)
def main():
    print("Hello world")
    path_file = filedialog.askopenfiles()
    # print(path_file)
    for i in path_file:
        f_name = i.name.split("/")[-1]
        print(f_name + " : " + i.mode)
        # print(i.mode)
        # print(i.name)
        pass
예제 #27
0
 def browse(self):
     '''opens a file browsing dialog and makes a list of the selected files'''
     self.message.set('Browsing...')
     self.progress['maximum'] = 29
     filename = askopenfiles(filetypes=(("Text files", "*.txt", ".TXT"),
                                        ("All files", "*.*")))
     self.converter.lst = (list(map(lambda f: f.name, filename)))
     self.file.set('{0} files selected'.format(len(self.converter.lst)))
     print(self.converter.lst)
     print(len(self.converter.lst))
예제 #28
0
def merge_pdf():
    filename = askopenfiles(mode='r', filetypes=[('PDF Files', '*.pdf')])
    mergedObject = PyPDF2.PdfFileMerger()
    for index, item in enumerate(filename):
        mergedObject.append(PyPDF2.PdfFileReader(item.name))

    mergedObject.write("merged.pdf")
    tmsg.showinfo(
        'PDF created',
        'PDF files are merged and is saved into the current working directory')
 def make_widgets(self):
     MLabel(self, text='文件对话框演示')
     self.label = MLabel(self, text='等待测试...')
     MButton(self, text='打开目录', command=lambda: self.print_result(filedialog.askdirectory()))
     MButton(self, text='打开文件', command=lambda: self.print_result(filedialog.askopenfile()))
     MButton(self, text='选择文件名', command=lambda: self.print_result(filedialog.askopenfilename()))
     MButton(self, text='选择多个文件名', command=lambda: self.print_result(filedialog.askopenfilenames()))
     MButton(self, text='打开多个文件', command=lambda: self.print_result(filedialog.askopenfiles()))
     MButton(self, text='保存为...', command=lambda: self.print_result(filedialog.asksaveasfile()))
     MButton(self, text='保存为文件名...', command=lambda: self.print_result(filedialog.asksaveasfilename()))
예제 #30
0
def selectFile(title = "None"):
    import tkinter.filedialog as filedialog
    import tkinter as tk

    root = tk.Tk()
    root.withdraw()
    fileList = []
    filez = filedialog.askopenfiles(parent = root, title = title)
    for i, v in enumerate(filez):
        fileList.append(v.name)
    return fileList
예제 #31
0
def main():
    # ask for location of file(s)
    root = tk.Tk()
    root.withdraw()
    # open individual file
    # file_path = filedialog.askopenfilename()
    # open multiple files
    file_path = filedialog.askopenfiles(filetypes=(("mp3 files", "*.mp3"),
                                                   ("all files", "*.*")))
    root.destroy()
    get_files(file_path)
예제 #32
0
def SelectFiles():
    fileSelected = filedialog.askopenfiles(mode='r', filetypes=[('Text','*.txt;*.doc;*.docx')])
    print(fileSelected)
    global files
    files = [];
    global iCurFile
    iCurFile=0
    for sel in fileSelected:
        files.append(sel.name)
    SVdataFile.set(str(files))
    ShowFile()
예제 #33
0
파일: smps.py 프로젝트: fanmei/atm-py
    def openFiles(self, scan_folder=''):
        """
        Launches a dialog to selct files for SMPS processing.

        Parameters
        -----------
        scan_folder:    string, optional
                        Starting folder for searching for files to process.  Default is empty.
        """
        _gui = tk.Tk()

        # Prompt the user for a file or files to process
        self.files = fd.askopenfiles(initialdi=scan_folder)
        _gui.destroy()