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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:10:42  来源:igfitidea点击:

Get file path from askopenfilename function in Tkinter

pythonpython-3.xtkinter

提问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 askopenfilenamefunction, 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 openfunction:

要打开使用 选择的文件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.TextIOWrapperobject or Noneif you press the cancelbutton.

我认为您正在使用askopenfile,它会打开选​​定的文件并返回一个_io.TextIOWrapper对象,或者None如果您按下取消按钮。

If you want to stick with askopenfileto get the file path of the file just opened, you can simply access the property called nameof the _io.TextIOWrapperobject 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 tkFileDialogfor Python 2) module, you can read this article.

如果你想了解更多关于在filedialog(或tkFileDialog为 Python 2)模块下定义的所有函数,你可以阅读这篇文章