要在默认应用程序中打开文件,可以使用import os

file = "C:\\Documents\\file.txt"

os.startfile(file)

这将在与文件扩展名关联的任何应用程序中打开文件。

但是也有一些缺点,所以如果你想对文件做一些更高级的处理(比如稍后关闭),你需要一个更高级的方法。您可以尝试my question here的解决方案,该解决方案显示如何使用subprocess.popen()跟踪文件,然后关闭它。总的来说:>>> import psutil

>>> import subprocess

>>> doc = subprocess.Popen(["start", "/WAIT", "file.pdf"], shell=True) #Stores the open file as doc

>>> doc.poll() #Shows that the process still exists (will return 0 if the /WAIT argument is excluded from previous line)

>>> psutil.Process(doc.pid).get_children()[0].kill() #Kills the process

>>> doc.poll() #Shows that the process has been killed

0

>>>

这将保留您作为doc对象打开的文件,以便以后可以轻松关闭它

更多推荐

python 打开excel并在屏幕上呈现_如何用Python打开Excel文件显示其内容?