22
votes

I would like to give users of my simple program the opportunity to open a help file to instruct them on how to fully utilize my program. Ideally i would like to have a little blue help link on my GUI that could be clicked at any time resulting in a .txt file being opened in a native text editor, notepad for example.

Is there a simple way of doing this?

6
What's the Gui framework you're using (PyGtk, Tkinter, ...)?! - ThomasH
@ThomasH: From the OP's other questions, it looks like he's using the PyQt application framework. - martineau

6 Answers

55
votes
import webbrowser
webbrowser.open("file.txt")

Despite it's name it will open in Notepad, gedit and so on. Never tried it but it's said it works.

An alternative is to use

osCommandString = "notepad.exe file.txt"
os.system(osCommandString)

or as subprocess:

import subprocess as sp
programName = "notepad.exe"
fileName = "file.txt"
sp.Popen([programName, fileName])

but both these latter cases you will need to find the native text editor for the given operating system first.

19
votes
os.startfile('file.txt')

From the python docs:

this acts like double clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated.

This way if your user changed their default text editor to, for example, notepad++ it would use their preference instead of notepad.

3
votes

If you'd like to open the help file with the application currently associated with text files, which might not be notepad.exe, you can do it this way on Windows:

import subprocess
subprocess.call(['cmd.exe', '/c', 'file.txt'])
3
votes

You can do this in one line:

import subprocess
subprocess.call(['notepad.exe', 'file.txt'])

You can rename notepad.exe to the editor of your choice.

1
votes

If anyone is getting an instance of internet explorer when they use import webbrowser, try declaring the full path of the specified file.

import webbrowser
import os

webbrowser.open(os.getcwd() + "/path/to/file/in/project")
#Gets the directory of the current file, then appends the path to the file

Example:

import webbrowser
import os

webbrowser.open(os.getcwd() + "/assets/ReadMe.txt")
#Will open something like "C:/Users/user/Documents/project/assets/ReadMe.txt"
0
votes

If you have any preferred editor, you can just first try opening in that editor or else open in a default editor.

ret_val = os.system("gedit %s" % file_path)
if ret_val != 0:
    webbrowswer.open(file_path)

In the above code, I am first trying to open my file in gedit editor which is my preferred editor, if the system does not have gedit installed, it just opens the file in the system's default editor.