Reputation: 5159
I'm attempting to use the tkinter filedialog
to get the user's choice of a file in my Python 3.4 program.
Previously, I was trying to use the Gtk FileChooserDialog, but I keep running into wall after wall getting it to work (here's my question about that.) So, I (attempted to) switched over to tkinter and use the filedialog.
Here's the code I'm using for the GUI:
import tkinter
from tkinter import filedialog
root = tkinter.Tk()
root.withdraw()
path = filedialog.askopenfile()
print(type(path)) # <- Not actually in the code, but I've included it to show the type
It works perfectly, except for the fact that it returns an <class '_io.TextIOWrapper'>
object instead of a string, like I expected/need it to.
Calling str()
on that doesn't work, and neither does using the io
module function getvalue()
.
Does anyone know how I could get the chosen file path as a string from the filedialog.askopenfile()
function?
Upvotes: 2
Views: 5462
Reputation: 298
I'm sure there are several ways, but what about getting path.name
? This should be a string.
print("type(path):", type(path))
# <class '_io.TextIOWrapper'>
print("path:", path)
# <_io.TextIOWrapper name='/some/path/file.txt' mode='r' encoding='UTF-8'>
print("path.name:", path.name)
# /some/path/file.txt
print("type(path.name):", type(path.name))
# <class 'str'>
Note that askopenfile
opens and returns the file in read mode by default. If you just want the filename and plan on opening it yourself later, try using askopenfilename
instead. See this link for more:
First you have to decide if you want to open a file or just want to get a filename in order to open the file on your own. In the first case you should use tkFileDialog.askopenfile() in the latter case tkFileDialog.askopenfilename().
Upvotes: 11