从 Tkinter 中的 askopenfilename 函数获取文件路径 [英] Get file path from askopenfilename function in Tkinter

查看:222
本文介绍了从 Tkinter 中的 askopenfilename 函数获取文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本来自动将一个文件中的一组特定文本更改为另一个具有不同名称的特定文本组.

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.

我想使用 askopenfilename 函数获取文件名,但是当我尝试打印文件名时,它返回:

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'>

我只需要文件名,因为 <_io.TextIOWrapper ...> 不可编写脚本.

I need just the file name because the <_io.TextIOWrapper ...> is not sub scriptable.

有什么建议可以去除多余的位?

Any suggestions to remove the extraneous bits?

推荐答案

askopenfilename() 返回选中文件的路径,如果没有选中文件则返回空字符串:

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))

要打开使用 askopenfilename 选择的文件,您可以简单地使用普通的 Python 构造和函数,例如 open 函数:

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()

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

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.

如果你想坚持使用 askopenfile 来获取刚刚打开的文件的文件路径,你可以简单地访问 _io 的名为 name 的属性.返回的 TextIOWrapper 对象:

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)

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

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.

这篇关于从 Tkinter 中的 askopenfilename 函数获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆