我正在尝试使用file = filedialog.askopenfile(initialdir='./')
打开文件,但我还需要知道为其他目的而打开的文件的名称。我知道如果用户选择文件,文件不是None
,否则它是这样的:
<_io.TextIOWrapper name='/Users/u/Desktop/e/config.py' mode='r' encoding='US-ASCII'>
但_io.TextIOWrapper
个对象不是可编写脚本的。
答案 0 :(得分:1)
通过建议,我发现存在另一个类似于messagebox.askopenfile
,askopenfilename
的函数,它不是直接打开文件,而只返回文件的名称。如果我们还想打开文件,我们可以手动打开并阅读它:
file_name = filedialog.askopenfilename(initialdir='./')
if file_name != '':
with open(file_name, 'r') as file:
string = ''
for line in file:
string += str(line)
print(string)
即使这是一种好方法,我仍然认为tkinter
应该直接使用messagebox.askopenfile
提供此功能。
通过Python目录导航,我们可以找到filedialog.py
文件,其中包含两个函数的规范,这两个函数非常相似:
def askopenfilename(**options):
"Ask for a filename to open"
return Open(**options).show()
askopenfile
def askopenfile(mode = "r", **options):
"Ask for a filename to open, and returned the opened file"
filename = Open(**options).show()
if filename:
return open(filename, mode)
return None
正如我们所看到的,第一个将调用的结果返回给show
函数,而第二个返回一个打开的文件。