Open a text file using notepad as a help file in python? - python

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?

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.

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.

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'])

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.

Here's somewhat of a cross-platform one (edit if you have any other methods):
import shutil, subprocess, os
file_name = "whatever.txt"
if hasattr(os, "startfile"):
os.startfile(file_name)
elif shutil.which("xdg-open"):
subprocess.call(["xdg-open", file_name])
elif "EDITOR" in os.environ:
subprocess.call([os.environ["EDITOR"], file_name])

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.

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"

Related

PYTHON AND BATCH SCRIPT: Run file if it exists and create if it doesn't

Full Disclaimer: I DO NOT KNOW PYTHON.
Hi Guys,
I have made an AutoHotKey Script for my volume keys. I would like to create a batch file which runs a python file (so if I change computers, I can easily create this scripts) which would do the following
Check if volume_keys.ahk exists in the D Drive
If it exists, run that;
If it doesn't exist, then create a file named volume_keys.ahk and add my script to it.
My script is:
^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down}
I know how to code the .bat file and just need help for the python point-of-view, but I request the community to check it:
#ECHO OFF
ECHO This script will run an AHK Script. If you want to stop this process from happening, then cross this window off.If you want to continye:
pause
cd d:
D:\run_volume_keys_ahk_script.py
I really appreciate any help by the community.
Thanks in advance
You can use the os library for this. Here's what the python program would look like.
import os
if os.path.isfile('D:\\volume_keys.ahk'): # check if it exists
os.system('D:\\volume_keys.ahk') # execute it
else:
with open('D:\\volume_keys.ahk', 'w') as f: # open it in w (write) mode
f.write('^!NumpadMult::Send {Volume_Mute} \
^!NumpadAdd::Send {Volume_Up} \
^!NumpadSub::Send {Volume_Down}') # Write to file
os.system('D:\\volume_keys.ahk') # execute
To activate the ahk script, you might want to use the subprocess module, of which I took the example from here
import subprocess
subprocess.call(["path/to/ahk.exe", "script.ahk"])
Note that you'll have to find the ahk executable on a computer before you can use the script, maybe you want to automatically check that too.
You can set the path you want to check for scripts in one string, and then add the filenames of your scripts as strings to a list. You can use listdir() from the os module to see any files and directories at a given path, then iterate over your scriptnames and check if it exists in that list of files. If it does, run it.
In this example I copy-pasted your script into a string as value for the key 'scriptname' in a dictionary, so that python can actually create the script file. This isn't really a neat way to do it though, you might want to have your scripts prepared in a directory next to your python script and copy them from there. See an example of how here
from os import listdir
from os.path import isfile, join
CHECK_PATH = "D:"
AHK_EXECUTABLE_PATH = "path/to/ahk.exe"
SCRIPTS_TO_CHECK = {'script1.ahk':"""^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down} """, 'script2.ahk':" some other script here"}
files_to_check = set(listdir(CHECK_PATH)) # using a set for fast lookup later
for scriptname, script in SCRIPTS_TO_CHECK.items():
if not scriptname in files_to_check:
print(f"script {scriptname} not found, creating it.")
with open(scriptname, 'w') as file:
file.write(script)
# else
subprocess.call(AHK_EXECUTABLE_PATH, scriptname)

how to modify txt file properties with python

I am trying to make a python program that creates and writes in a txt file.
the program works, but I want it to cross the "hidden" thing in the txt file's properties, so that the txt can't be seen without using the python program I made. I have no clues how to do that, please understand I am a beginner in python.
I'm not 100% sure but I don't think you can do this in Python. I'd suggest finding a simple Visual Basic script and running it from your Python file.
Assuming you mean the file-properties, where you can set a file as "hidden". Like in Windows as seen in screenshot below:
Use operating-system's command-line from Python
For example in Windows command-line attrib +h Secret_File.txt to hide a file in CMD.
import subprocess
subprocess.run(["attrib", "+h", "Secret_File.txt"])
See also:
How to execute a program or call a system command?
Directly call OS functions (Windows)
import ctypes
path = "my_hidden_file.txt"
ctypes.windll.kernel32.SetFileAttributesW(path, 2)
See also:
Hide Folders/ File with Python
Rename the file (Linux)
import os
filename = "my_hidden_file.txt"
os.rename(filename, '.'+filename) # the prefix dot means hidden in Linux
See also:
How to rename a file using Python

How to open a file for browsing (as if one opened it manually)

I am trying to use Python to open a file for visual browsing, i.e. as if one double clicked a file to view it. I have tried numerous searches but because the words are very similar with doing file I/O I could not come across the appropriate information.
I think this is a very simple question / answer and I apologize if the answer was right in front of my nose.
Ideally it would just be a call on a given file path and Python would know the appropriate application to pair in case it was an extension like .pdf.
os.startfile()
os.system() but the parameters passed varies according to the OS
Windows: Start fileName
Mac: open fileName
Linux: oowriter fileName
: gnome-open fileName
: kde-open fileName etc...
Example:
fileName="file.pdf" //Path to the file
1. os.startfile(fileName)
2. os.system("start %s")%fileName
On Windows you can use os.startfile().
os.startfile("C:\\Users\\your\\file.pdf")

How to use the Windows Explorer or Finder file dialogues in Tkinter/Python2.7.3?

Among other things, I am currently trying to create a basic text editor which can open text files, edit them, and then save them. I have used this Tkinter dialogue for the GUI 'file manager,' but I was wondering if anyone knew the way to access the one that comes default on Windows?
Thanks!
Technical Things:
OS: Windows 7
Language: Python 2.7.3
EDIT 1
By the DEFAULT file dialogue, I mean the windows explorer dialogue:
I also use mac. Assuming that my application is cross-platform, would there be any way for me to have the program check what the os was, and then open either Finder or Windows Explorer.
I need the program to be able to save and open items in different commands. How would I do this?
It's not exactly clear what you're asking, since the one that tkinter comes with is default in Windows. Here's another link for that, just in case you got mixed up somewhere along the line. Remember that you can set it so it only finds a certain type of file, starts in a specific place, returns the filename or directory, or even open the file (I think)
If you mean the Windows Explorer you can open it and close it with pywin32, but not much else. Taken from this answer
import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
try importing tkFileDialog:
import tkFileDialog as tkfd
def save():
savenm = tkfd.asksaveasfile()
f = open(savenm.name,"w")
# then put what to do with the opened file
def open():
opennm = tkfd.askopenfile()
f = open(savenm.name,"r")
# then put what to do with the opened file
then make a button that uses the functions:
import Tkinter as tk
root=tk.Tk()
SAVELOADFRAME = tk.Frame(root)
SAVELOADFRAME.pack()
savebtn = Button(SAVELOADFRAME,text="Save",command=save)
savebtn.pack(side=LEFT)
root.mainloop()
loadbtn = Button(SAVELOADFRAME,text="Open",command=open)
loadbtn.pack(side=RIGHT)
maybe if you have a notepad box you might want to insert the text from the file into the tk.Text widget. The above code only works for text based files really (e.g. *.js, *.txt, *.py) not *.exe, *.dll, etcetera.
hope that solves your problem :^)

Passing a Hebrew file name as command line argument in Windows

I have a small Python program. I use the the Windows registry to enable the opening of files using the right-click context menu. My registry entry:
C:\Users\me\projects\mynotepad\notepad.exe "%1"
When I try and open a file with a Hebrew name using my right-click context menu, I get the file name as question marks, and I get an exception while trying to get the file size.
Here is my code:
file_name = sys.argv[1]
file_size = os.path.getsize(unicode(file_name))
I have tried this:
file_name = sys.argv[1].decode("cp1255").encode('utf-8')
file_size = os.path.getsize(unicode(file_name))
But it didn't work.
Any advice?
Turns out it's a problem. See here for the solution. You need to resort to Windows API to get the arguments.

Categories