如何用Python打开Excel文件来显示其内容?
我想用Python打开一个excel文件来显示满足的数据,就像我们用鼠标双击它一样。
我search了一段时间,但似乎所有的页面都在讨论如何读取和写入代码的Excel文件,而不是显示内容给用户。
那么,有没有解决我的问题?
非常感谢。
要在其默认应用程序中简单地打开文件,可以使用
import os file = "C:\\Documents\\file.txt" os.startfile(file)
这将在任何与文件扩展名关联的应用程序中打开文件。
但是有一些缺点,所以如果你想对文件进行一些更高级的处理(比如稍后closures),你需要一个更高级的方法。 你可以在这里试试我的问题的解决scheme,它显示了如何使用subprocess.popen()
跟踪文件,然后closures它。 总体思路如下:
>>> 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
对象打开的doc
以便稍后可以轻松closures它
为了补充wnnmaw的回答,subprocess.popen支持上下文pipe理和'with'操作符,它提供了一个很好的,干净的Pythonic方法来处理文件的打开和closures。 基本上,没有必要用这种方法明确地closures文件。
import psutil import subprocess with subprocess.Popen(["start", "/WAIT", "file.pdf"], shell=True) as doc: # use 'doc' here just as you would the file itself doc.poll() doStuff(doc) for line in readline(doc): etc, etc... # then just continue with the rest of your code.
'with'语句将自动处理你的开头和结尾,这很好,很容易阅读。 必须记住的一个警告是,这一次只适用于一个文件。 如果你的函数要一次处理多个文件,你最好手动处理打开/closures。
如果您只想将控制权交给Excel(完成后依靠最终用户在Excel中closures文件),请参阅wnnmaw答案的第一部分。