Issue
I am writing a script to automate changing a particular set of text in one file into a particular set in another with a different name.
I want to get the name of the file using the askopenfilename
function, but when I try to print the file name, it returns:
<_io.TextIOWrapper name='/home/rest/of/file/path/that/I/actually/need.txt' mode='w' encoding='ANSI_X3.4-1968'>
I need just the file name because the <_io.TextIOWrapper ...>
is not sub scriptable.
Any suggestions to remove the extraneous bits?
Solution
askopenfilename()
returns the path of the selected file or empty string if no file is selected:
from tkinter import filedialog as fd
filename = fd.askopenfilename()
print(len(filename))
To open the file selected with askopenfilename
, you can simply use normal Python constructs and functions, such as the open
function:
if filename:
with open(filename) as file:
return file.read()
I think you are using askopenfile
, which opens the file selected and returns a _io.TextIOWrapper
object or None
if you press the cancel button.
If you want to stick with askopenfile
to get the file path of the file just opened, you can simply access the property called name
of the _io.TextIOWrapper
object returned:
file = fd.askopenfile()
if file:
print(file.name)
If you want to know more about all the functions defined under the filedialog
(or tkFileDialog
for Python 2) module, you can read this article.
Answered By - nbro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.