Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

python - Get file path from askopenfilename function in Tkinter

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...