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 littl
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.
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.
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.
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.
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"
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'])