Python 从 Tkinter 中的 askopenfilename 函数获取文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28373288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get file path from askopenfilename function in Tkinter
提问by MatthewC
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:
我想使用该askopenfilename
函数获取文件名,但是当我尝试打印文件名时,它返回:
<_io.TextIOWrapper name='/home/rest/of/file/path/that/I/actually/need.txt' mode='w' encoding='ANSI_X3.4-1968'>
<_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.
我只需要文件名,因为<_io.TextIOWrapper ...>
它不可编写脚本。
Any suggestions to remove the extraneous bits?
有什么建议可以删除多余的位吗?
采纳答案by nbro
askopenfilename()
returns the path of the selected file or empty string if no file is selected:
askopenfilename()
如果未选择文件,则返回所选文件的路径或空字符串:
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:
要打开使用 选择的文件askopenfilename
,您可以简单地使用普通的 Python 构造和函数,例如open
函数:
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 cancelbutton.
我认为您正在使用askopenfile
,它会打开选定的文件并返回一个_io.TextIOWrapper
对象,或者None
如果您按下取消按钮。
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:
如果您想坚持askopenfile
获取刚刚打开的文件的文件路径,您可以简单地访问返回name
的_io.TextIOWrapper
对象的调用属性:
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.
如果你想了解更多关于在filedialog
(或tkFileDialog
为 Python 2)模块下定义的所有函数,你可以阅读这篇文章。