有没有一种方法可以指定然后使用Python打开文件?

时间:2019-04-15 17:58:55

标签: python-3.x tkinter filesystems

我正在尝试制作一个程序,该程序将允许用户从其计算机中选择一个文件,然后将其打开。我一直在尝试使用Python执行此操作,并且...

filedialog.askopenfilenames()

...带有此Tkinter小部件。

我可以从中成功获取文件路径,但是如何使用它实际打开文件? (我试图在其默认应用程序中打开它,而不仅仅是将其打印到Python控制台。)我尝试使用

from subprocess import call
call(['xdg-open','filename'])

用“文件”(存储文件名的变量)替换“文件名”,但出现以下错误:

Traceback (most recent call last):
  File "/Users/charlierubinstein/Documents/Search Engine.py", line 9, in <module>
    call(['xdg-open', files])
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 267, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1275, in _execute_child
    restore_signals, start_new_session, preexec_fn)
TypeError: expected str, bytes or os.PathLike object, not tuple
到目前为止,我的代码:

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from subprocess import call


files = filedialog.askopenfilenames()

call(['xdg-open', files])  
window.mainloop()

如前所述,理想情况下,该程序允许用户选择一个文件,然后在其默认应用程序中打开该文件。

1 个答案:

答案 0 :(得分:1)

您使用askopenfilenames()(名称末尾带有 s

它允许您选择许多文件,因此即使选择了一个文件,它也会返回包含所有选定文件的元组
(如果取消选择,则为空元组)

所以您必须从元组中获取第一个元素

call(['xdg-open', files[0] ])  

或使用askopenfilename()(名称末尾没有 s ),您将获得单个字符串。

filename = filedialog.askopenfilename() # without `s` at the end

call(['xdg-open', filename])  
相关问题