如何在 Python 中打开外部程序中的文件?
我想知道如何根据文件的扩展名在记事本和图片查看器等程序中打开文件.我在 Windows 上使用 Python 3.3.
I'm wondering how to open files in programs such as Notepad and Picture Viewer depending on the extension the file has. I'm using Python 3.3 on Windows.
我做了一些研究,人们提到了一个名为 Image
的模块,但是当我尝试导入这个模块时,我得到了一个 ImportError.
I've done some research and people have mentioned a module named Image
, but when I try and import this module I get an ImportError.
这是我目前所拥有的:
def openFile():
fileName = listbox_1.get(ACTIVE)
if fileName.endswith(".jpg"):
fileName.open()
我还需要在记事本中打开 HTML 和 JSON 文件.
I will also have HTML and JSON files that I will need to open in Notepad.
使用这个可以用默认程序打开任何文件:
Use this to open any file with the default program:
import os
def openFile():
fileName = listbox_1.get(ACTIVE)
os.system("start " + fileName)
如果你真的想使用某个程序,比如记事本,你可以这样做:
If you really want to use a certain program, such as notepad, you can do it like this:
import os
def openFile():
fileName = listbox_1.get(ACTIVE)
os.system("notepad.exe " + fileName)
此外,如果您在打开文件之前需要一些 if 检查,请随时添加它们.这仅向您展示了如何打开文件.
Also if you need some if checks before opening the file, feel free to add them. This only shows you how to open the file.