IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Tkinter Python Discussion :

Importer un fichier et coller son contenu dans un fichier .txt [Python 2.X]


Sujet :

Tkinter Python

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2014
    Messages
    23
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2014
    Messages : 23
    Points : 15
    Points
    15
    Par défaut Importer un fichier et coller son contenu dans un fichier .txt
    Bonjour,

    Voici mon programme de base :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    from Tkinter import *
     
    def dispatch_yview (*args):
        """
            cette fonction dispatche les commandes de la scrollbar
            VERTICALE entre les deux canevas;
        """
        canvas.yview(*args)
        canvas2.yview(*args)
    # end def
     
    def ensure_float (expression):
        """
            évalue puis convertit une expression en float,
            retourne 0.0 si erreur;
        """
        try:
            return float(eval(str(expression)))
        except Exception as e:
            #~ print "une erreur est survenue :", str(e)
            return 0.0
        # end try
    # end def
     
    def ok():
        """
            validation des données, calculs et création du nouveau
            fichier de sortie;
        """
        with open("matrice.txt") as file_in:
            lines = file_in.readlines()
        # end with
     
        # Sélection de la matrice VERTEX_LIST :
        indice_vertexListDebut= lines.index("  VERTEX_LIST\n")
        matrice_lines1=lines[indice_vertexListDebut+2:]
     
        indice_vertexListFin= matrice_lines1.index("  }\n")
        lines2=matrice_lines1[:indice_vertexListFin]
        #fin sélection
     
        # stockage des deux encadrements
        str1=''
        avant=lines[:indice_vertexListDebut+3]
        print 'avant : ', avant
        for i in range (len(avant)-1):
            str1=str1+avant[i]
     
        str3=''
        apres=matrice_lines1[indice_vertexListFin:]
        for i in range (len(apres)-1):
            str3=str3+apres[i]
        # fin stockage
     
        decimals = E4.get()
        entries = [E1.get(), E2.get(), E3.get()]
        str_data = ""
        for line in lines2:
            # si line = "[nnn, nnn, nnn]" inutile de réinventer la roue:
            # c'est déjà la structure d'une liste Python [nnn, nnn, nnn]
            values = eval(line) if line.strip() else []
            data = []
            for (i, j) in zip(values, entries):
                # il faut évaluer chaque valeur séparément !
                if '*' in j :
                    j=j.replace('*','')
                    sum_up= ensure_float(i) * ensure_float(j)
                elif '/' in j :
                    j=j.replace('/','')
                    sum_up= ensure_float(i) / ensure_float(j)
                else:
                    sum_up = ensure_float(i) + ensure_float(j)
                if decimals:
                    sum_up = round(sum_up, int(decimals))
                # end if
                data.append(sum_up)
            # end for
            str_data += str(data) + '\n'
        # end for
        str_data=str1+str_data+str3
     
        with open('matrice2.txt', 'w') as file_out:
            file_out.write(str_data)
        # end with
        canvas2.itemconfigure(c2_text_id, text=str_data)
        lbl_output.configure(text="Operation succeeded!")
    # end def
     
    # Création de fenêtre
    root = Tk()
    root.title("coordinate change")
    root.resizable(width=False, height=False)
     
    # Label, Entry
    Message(root, text="""Notice:
    This program allows to increase or decrease one \
    of the coordinates (X, Y or Z) of a [X,Y,Z] matrice such as:
    [ [15, 1.454, 0.1], [12.1, 5.2, 78], ..., [0.3, 0, 45] ]
    Please copy your matrice in a file whose the name is 'matrice.txt'.
    Put the file in the same directory than this program.
    The new matrice will be in the file named 'matrice2.txt'.""",
    font="sans 10", width=360).grid(row=0, column=1, padx=5)
     
    my_font = "helvetica 14 underline"
     
    frame = Frame(root)
    frame.grid(row=0, column=0)
     
    Label(frame, text='insert values:', font=my_font).grid(row=0, column=1)
    Label(frame, text='X:', font=my_font).grid(padx=5, sticky=E)
     
    E1 = Entry(frame)
    E1.grid(row=1, column=1)
    #~ E1.insert(0, 0) # risque de notation *octale* e.g. 025 = 21 /!\
     
    Label(frame, text='Y:', font=my_font).grid(padx=5, sticky=E)
     
    E2 = Entry(frame)
    E2.grid(row=2, column=1)
     
    Label(frame, text='Z:', font=my_font).grid(padx=5, sticky=E)
     
    E3 = Entry(frame)
    E3.grid(row=3, column=1)
     
    Label(frame, text='Round values\nup to (decimals):').grid(padx=5, sticky=E)
     
    E4 = Entry(frame)
    E4.grid(row=4, column=1, sticky=SW)
     
    Button(frame, text='OK', width=10, command=ok).grid(row=4, column=2, padx=10, sticky=S)
     
    lbl_output = Label(root, fg="red")
    lbl_output.grid(row=2, column=1)
     
    frame = Frame(root)
    frame.grid(row=1, column=0, columnspan=2)
     
    txt_options = dict(font="sans 12 bold", fill="blue", anchor=NW)
     
    Label(frame, text='matrice.txt contents:', font=my_font).grid(row=0, column=0)
     
    with open("matrice.txt") as file_in:
        lines = file_in.read().strip()
    # end with
     
    canvas = Canvas(frame, bg="white")
    canvas.grid(row=1, column=0, sticky=NW+SE)
    canvas.create_text(0, 0, text=lines, **txt_options)
     
    # horizontal scrollbar
    hbar = Scrollbar(frame, orient=HORIZONTAL)
    hbar.grid(row=2, column=0, sticky=NW+SE)
    # vertical scrollbar pour les 2
    vbar = Scrollbar(frame, orient=VERTICAL)
    vbar.grid(row=1, column=3, sticky=NW+SE)
    # connecting people...
    canvas.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=canvas.bbox(ALL),
    )
    hbar.configure(command=canvas.xview)
    vbar.configure(command=canvas.yview)
     
    frame.columnconfigure(1, minsize=5)
     
    Label(frame, text='matrice2.txt contents:', font=my_font).grid(row=0, column=2)
     
    canvas2 = Canvas(frame, bg="white")
    c2_text_id = canvas2.create_text(0, 0, **txt_options)
    canvas2.grid(row=1, column=2, sticky=NW+SE)
     
    # horizontal scrollbar
    hbar = Scrollbar(frame, orient=HORIZONTAL)
    hbar.grid(row=2, column=2, sticky=NW+SE)
     
    # connecting people...
    canvas2.configure(
        xscrollcommand=hbar.set,
        yscrollcommand=vbar.set,
        scrollregion=canvas.bbox(ALL),
    )
    hbar.configure(command=canvas2.xview)
    vbar.configure(command=canvas2.yview)
     
    # special dispatch between 2 canvases
    vbar.configure(command=dispatch_yview)
     
    Button(root, text="Quit", command=root.destroy).grid(row=2, column=1, padx=5, pady=5, sticky=SE)
     
    root.mainloop()
    Je cherche à ce que l'utilisateur puisse directement aller chercher son fichier qui a pour extension .geometry.mdl et que le contenu de ce fichier soit collé dans un fichier texte.
    Concernant l'importation, je crois qu'il faut que je m'aide ce code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    from Tkinter import *
     
    import tkFileDialog as FD
     
     
    class TkFileDialogExample(TK.Tk):
        """
            cette classe bla bla bla... explications
        """
     
        def __init__(self):
     
            # superclass inits
            TK.Tk.__init__(self)
     
            # member inits
            self.file_in = ""
     
     
            # widget inits
            TK.Label(
                self,
                text="Input file",
            ).grid(row=0, column=0, sticky=TK.W)
     
            self.input_tb = TK.Entry(self, width=30)
            self.input_tb.grid(row=0, column=1)
     
            TK.Button(
                self,
                text="browse",
                command=self.dlg_file_open, # avoid confusing names /!\
            ).grid(row=0, column=2)
     
     
        # end def
     
     
        def dlg_file_open(self):
            """
                cette méthode bla bla bla... explications
            """
     
            self.file_in = FD.askopenfilename(
     
                filetypes=[("all files", ".*"), ("text files", ".txt")],
            )
     
            self.input_tb.delete(0, TK.END)
     
            self.input_tb.insert(0, self.file_in)
     
        # end def
     
     
        def dlg_file_save_as(self):
            """
                cette méthode bla bla bla... explications
            """
     
     
     
            self.output_tb.delete(0, TK.END)
     
     
     
        # end def
     
     
        def send(self):
            """
                cette méthode bla bla bla... explications
            """
     
            print "input file:", self.file_in
     
     
     
        # end def
     
    # end class TkFileDialogExample
     
     
    if __name__ == "__main__":
     
        TkFileDialogExample().mainloop()
     
    # end if
    Première question : Comment la fenêtre fait elle pour s'afficher à partir de ce dernier code ? TkFileDialogExample() appelle la classe mais après comment cela se fait-il que le programme rentre dans les fonctions ?
    Deuxième question : Savez-vous comment on pourrait stocker le contenu d'un fichier .geometry.mdl à partir de ce code ?

    Merci.

  2. #2
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par adrbessy Voir le message
    Bonjour,

    Je cherche à ce que l'utilisateur puisse directement aller chercher son fichier qui a pour extension .geometry.mdl et que le contenu de ce fichier soit collé dans un fichier texte.
    Bonjour, vous n'avez besoin de rien d'autre que de tkFileDialog (Python2) ou tkinter.filedialog (Python3).



    Concernant l'importation, je crois qu'il faut que je m'aide ce code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    from Tkinter import *
     
    import tkFileDialog as FD
     
     
    class TkFileDialogExample(TK.Tk):
        """
            cette classe bla bla bla... explications
        """
     
        def __init__(self):
     
            # superclass inits
            TK.Tk.__init__(self)
     
            # member inits
            self.file_in = ""
     
     
            # widget inits
            TK.Label(
                self,
                text="Input file",
            ).grid(row=0, column=0, sticky=TK.W)
     
            self.input_tb = TK.Entry(self, width=30)
            self.input_tb.grid(row=0, column=1)
     
            TK.Button(
                self,
                text="browse",
                command=self.dlg_file_open, # avoid confusing names /!\
            ).grid(row=0, column=2)
     
     
        # end def
     
     
        def dlg_file_open(self):
            """
                cette méthode bla bla bla... explications
            """
     
            self.file_in = FD.askopenfilename(
     
                filetypes=[("all files", ".*"), ("text files", ".txt")],
            )
     
            self.input_tb.delete(0, TK.END)
     
            self.input_tb.insert(0, self.file_in)
     
        # end def
     
     
        def dlg_file_save_as(self):
            """
                cette méthode bla bla bla... explications
            """
     
     
     
            self.output_tb.delete(0, TK.END)
     
     
     
        # end def
     
     
        def send(self):
            """
                cette méthode bla bla bla... explications
            """
     
            print "input file:", self.file_in
     
     
     
        # end def
     
    # end class TkFileDialogExample
     
     
    if __name__ == "__main__":
     
        TkFileDialogExample().mainloop()
     
    # end if
    Non, désolé : vous n'avez pas besoin de ce code pour y arriver ; tkFileDialog vous fournit déjà tout ce dont vous avez besoin.

    Première question : Comment la fenêtre fait elle pour s'afficher à partir de ce dernier code ?
    ce code ne fonctionne pas en l'état.

    Sortie console :

    Traceback (most recent call last):
      File "./forum.py", line 9, in <module>
        class TkFileDialogExample(TK.Tk):
    NameError: name 'TK' is not defined
    
    En corrigeant ce qui ne va pas :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    from Tkinter import *
     
    import tkFileDialog as FD
     
     
    class TkFileDialogExample(Tk):
        """
            cette classe bla bla bla... explications
        """
     
        def __init__(self):
     
            # superclass inits
            Tk.__init__(self)
     
            # member inits
            self.file_in = ""
     
     
            # widget inits
            Label(
                self,
                text="Input file",
            ).grid(row=0, column=0, sticky=W)
     
            self.input_tb = Entry(self, width=30)
            self.input_tb.grid(row=0, column=1)
     
            Button(
                self,
                text="browse",
                command=self.dlg_file_open, # avoid confusing names /!\
            ).grid(row=0, column=2)
     
     
        # end def
     
     
        def dlg_file_open(self):
            """
                cette méthode bla bla bla... explications
            """
     
            self.file_in = FD.askopenfilename(
     
                filetypes=[("all files", ".*"), ("text files", ".txt")],
            )
     
            self.input_tb.delete(0, END)
     
            self.input_tb.insert(0, self.file_in)
     
        # end def
     
     
        def dlg_file_save_as(self):
            """
                cette méthode bla bla bla... explications
            """
     
     
     
            self.output_tb.delete(0, END)
     
     
     
        # end def
     
     
        def send(self):
            """
                cette méthode bla bla bla... explications
            """
     
            print "input file:", self.file_in
     
     
     
        # end def
     
    # end class TkFileDialogExample
     
     
    if __name__ == "__main__":
     
        TkFileDialogExample().mainloop()
     
    # end if
    La classe TkFileDialogExample dérive de Tk (la fenêtre principale de Tkinter) et non pas de tkFileDialog (attention au piège des noms de classe !).

    Elle s'affiche donc comme n'importe quelle fenêtre Tk() au moment où l'on appelle mainloop().

    TkFileDialogExample() appelle la classe mais après comment cela se fait-il que le programme rentre dans les fonctions ?
    C'est le bouton :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
            Button(
                self,
                text="browse",
                command=self.dlg_file_open, # avoid confusing names /!\
            ).grid(row=0, column=2)
    qui lance self.dlg_file_open() lorsqu'on clique dessus.

    Deuxième question : Savez-vous comment on pourrait stocker le contenu d'un fichier .geometry.mdl à partir de ce code ?
    Merci.
    Vous n'avez pas besoin de stocker le contenu d'un fichier *.geometry.mdl, vous avez juste besoin de copier ce fichier dans un fichier *.txt.

    à moins que vous n'ayiez à convertir les données binaires issues du fichier d'origine avant de les exporter dans un fichier texte de destination, évidemment.

    mais si les données ne changent pas entre *.geometry.mdl et *.txt, ce n'est qu'une copie de fichier (ne pas se laisser abuser par les noms des fichiers).

    @+.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 9
    Dernier message: 07/02/2013, 10h22
  2. Réponses: 3
    Dernier message: 15/02/2010, 09h56
  3. Réponses: 4
    Dernier message: 25/01/2010, 16h07
  4. Réponses: 1
    Dernier message: 01/06/2009, 05h12
  5. [VBA-E]Ecrire dans un fichier sans l'ouvrir (ou dans un fichier invisible)
    Par bandit boy dans le forum Macros et VBA Excel
    Réponses: 11
    Dernier message: 29/05/2006, 17h14

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo