Error printing on screen tkinter python 2.7

-1

There is a problem when starting the function, could you help me?

from Tkinter import *
from tkFileDialog import *
import getpass
import os

usuario = getpass.getuser()   
ventana = Frame(height=400,width=400,background="black")
ventana.pack()

def elegir():
    archivo=askopenfile(mode="r",initialdir="C:/Users/%s/Desktop" % usuario,
        filetypes=(("Documento word","*.doc",),("ALL FILES","*.*.*")))
    directorio = os.path.split(archivo)[0] 
    print(directorio)

boton_eleg = Button(ventana,text="SELECCIONE EL ARCHIVO",command=elegir).place(x=10,y=220)      

ventana.mainloop()  

I want to print the route only, but I run into the problem in the console.

I would appreciate a help.

    
asked by Deivid 22.12.2016 в 10:30
source

1 answer

0

askopenfile returns an object of type file or None if the file is not selected or can not be opened. You simply can not apply os.path.split() on either of the two.

To get the route you can simply access the attribute name of object file :

from Tkinter import *
from tkFileDialog import *
import getpass
import os

usuario = getpass.getuser()
ventana = Frame(height=400,width=400,background="black")
ventana.pack()

def elegir():
    archivo=askopenfile(mode="r", initialdir="C:/Users/%s/Desktop" % usuario,
        filetypes=(("Documento word","*.doc",),("ALL FILES","*.*.*")))
    directorio = ''
    if archivo:
        directorio = os.path.split(archivo.name)[0]
        print directorio

boton_eleg = Button(ventana,text="SELECCIONE EL ARCHIVO",command=elegir).place(x=10,y=220)

ventana.mainloop()

If the route is for example:

  

C: /Users/Alguien/Desktop/documento.doc

directorio contains when applying os.path.split()[0] :

  

C: / Users / Someone / Desktop

As Chema Cortés has commented to you, it could be simpler to use askopenfilename that already returns the file path and then open it as any file in Python using open() .

    
answered by 22.12.2016 в 17:34