Python script opening wrong file in Atom? - python

Instead of opening all the programs and files one by one to edit my website when I turn on my computer, I want to execute a python script to open them all for me. However, when I run it, it is always opening an index.html file in a folder titled 'index'. I want it to open up say, webpages.html in the 'webpages' folder.
#!/usr/bin/env python
import os, webbrowser, subprocess
os.chdir('C:/Users/Bruin/Desktop/My_Webpage')
current_path = os.getcwd()
file_to_open = input('What filename to open?')
print("hello")
#subprocess.call([r'C:\Users\Bruin\AppData\Local\atom\atom.exe', r'C:\Users\Bruin\Desktop\My_Webpage\'' + file_to_open + r'\'' + file_to_open + r'.html'])
subprocess.call([r'C:\Users\Bruin\AppData\Local\atom\atom.exe', r'C:\Users\Bruin\Desktop\My_Webpage\webpages\webpage.html'])
webbrowser.open('file:///C:/Users/Bruin/Desktop/My_Webpage/index/index.html', new=2)
I commented out where I used the inputed variable because even explicitly typing in what I want to open directly into the script, it is not working. It is opening up in the browser just fine.
I am also working in PyCharm, do not know if that matters. It didn't work in IDLE either. I'm lost on where to go.

Related

How to use the Open With feature with Python?

I'm currently working with a python script that has the following code. It opens a file that has JSON text and determines a value from that.
browseFiles()
def browseFiles():
global fileName
fileName = filedialog.askopenfilename(title = "Select a File", filetypes = (("All Files","*.*")))
# Open the File in Read Mode
fileFile = open(fileName, "r")
# Read the file
fileContent = fileFile.read()
# Render the JSON
fileJSON = json.loads(fileContent)
# Determine the ID
myID = fileJSON["key"]
# Update the Status
windowRoot.title(myID)
... remaining code
fileFile.close()
However, it is less convenient to open the program every time, and then navigate to it.
Windows has an 'Open With' feature in File Explorer where we can right-click a file and open it with apps such as Word, etc.
How to implement this in a Python script? Should I consider creating a .exe of this script first, and if yes then which library would be most suitable for this? (Considering it is a very small and simple utility)
Some extra information that is probably unwanted: I'm using Tkinter for the GUI.
(By the way, if this question already exists on StackOverFlow or any other website, then please comment the link instead of just marking it as duplicate. I tried searching a lot and couldn't find anything)
Regards,
Vivaan.
simple example:
import sys
try:
#if "open with" has been used
print(sys.argv[1])
except:
#do nothing
pass
usage example:
import sys
from tkinter import filedialog
filetypes = (('Text files', '*.txt'),('All files', '*.*'))
#if filename is not specified, ask for a file
def openfile(filename = ''):
#print contents of file
if filename == '':
filename = filedialog.askopenfilename(title='Open A File',filetypes=filetypes)
with open(filename,'r', encoding="utf-8") as file:
read = file.read()
print(read)
try:
#if "open with" has been used
openfile(filename = sys.argv[1])
except:
#ask for a file
openfile()
then compile it to exe with nuitka (or whatever tool you use),
and try it.
or (for testing, without having to compile it every time you make a change):
make a .bat file
#echo off
py program.py %*
pause
Then every time you want to run it,
you open with that file.
what you need is added new item into right click context menu.
You can take sample registry code below, modify the path to your py script C:\your_script.py and save it as anything end with .reg extension then double click to execute this registry file.
after that, you should see open with my_py when u right click on the target file
from your py script side, replace the filedialog code with fileName = sys.argv[1]
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\shell\open with my_py\command]
#="python C:\\your_script.py %1"
*** Please be cautious with the registry code as wrong registry hack can be troublesome
refer this for manually modify the registry
Found another question with answers that helped me. Posting this for other people who might find this question.
answer from Roy Cai:
My approach is to use a redirect .bat file containing python someprogram.py %1. The %1 passes the file path into the python script which can be accessed with
from sys import argv
argv[1]

how can I get the complete path for my python code

I would like to print the path and file name of my python code.
For example, " my_directory/my_subdirectory/my_python_code_name "
I tried different things, like import sys, os
followed by any of those below:
sys.argv[0]
print('sys.argv[0] =', sys.argv[0])
print('full path =', os.path.abspath(pathname))
os.path.realpath(__file__)
None of those works.
I am using spyder.
I'm not sure if this is late, but maybe this answer can help someone else. In general in order to get a file path you would do something like this:
import os
print('Full path:', __file__)
print('Full path without file name:', os.getcwd())
print('Name of the file:', os.path.basename(__file__))
However using __file__ may not work for you if you are using an interactive prompt as the prompt from Spyder or Jupyter Notebook.
In this latter case you could write in a cell the following:
%%javascript
IPython.notebook.kernel.execute('notebook_name = "' + IPython.notebook.notebook_name + '"')
With this you are defining the variable notebook_name with the name of the .ipynb file from which you are executing.
To better answer the question, in Spyder you can execute code from a temp python file which works exactly as a normal python script, and for which you can use the first fragment of code above.
From your answers however I understand that you are executing code from the Spyder IPython Console that doesn't really have a name of a file to display. You should consider using a script if you really want a name to display.

How to change where the file being created when using .open("fileName", "w+") function in Python(VS code environment)?

How can I change where the textfile.txt should be created in VS IDE?
This is the whole structure of the project
Learning Python
>.sfdx
>.vscode
>Debug
>Exercise File
The current file I am editing on is somewhere in Exercise File, however when the textile.txt is created by Python, it is located in the folder of Learning Python.
Learning Python
>.sfdx
>.vscode
>Debug
>Exercise File
>textfile.txt
Thank you for reading my question, hope it is clear enough!
You can use the own python to do that, using getcwd and chdir methods from os. The getcwd return the current working directory and chdir is used to change the working directory.
import os
current_path = os.getcwd()
print(current_path)
new_path = "/your/path"
os.chdir(new_path)
print(new_path)
Just specify the full path of the file in the open function.
f = open(r"C:\Users\deepstop\Documents\textfile.txt", "w+")
The r in front of the string is important. It means "raw" and prevents the backslashes in the string from being interpreted as escape characters.

Opening and Reading files in Python [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 3 months ago.
For some reason I am unable to open my .txt file within python.
I have the .py and .txt file within a folder. Both files are stored Workspace -> Folder(Crash Course) -> Folder(Lessons) -> Folder(Ch 10)-> both files within this Ch 10 Folder.
I am getting
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
With the code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
This is less for the person that asked the question but more for people like myself that come here from Python Crash Course with the same question and don't get the answer they were looking for:
If, like me, you were running the code from your text editor (in my case VS Code), it's possible that the terminal window within the editor wasn't in the proper directory. I didn't realize myself, because I was thinking that because I opened the .py file from the correct working directory in the terminal that everything should work as planned. It wasn't until I realized that the terminal in the editor is a separate instance (thus making the present working directory home instead of my folder for PCC work) that I was able to get the program to run as intended.
In short, navigate to the proper directory in your editor's terminal instance and the program should run as intended.
Hope this helps!
image with terminal open on desktop and in text editor to show working directory difference
I used full path of the file along with r, which is for raw string. Worked for me.
example:
filename = **r**'C:\Python\CrashCourse\pi_digits.txt'
with open(filename) as file_object:
content = file_object.read()
print(content)
The path to the file is relative to where you run the python file from, not from where the python file is located.
Either run your code from the same directory as the files, or make the file path absolute, based on the python file's location.
import os
with open(os.path.join(os.path.dirname(__file__), 'pi_digits.txt')) as file_object:
contents = file_object.read()
print(contents)
Hope that helps
Try this:
with open('c:\\Workspace\\Crash Course\\Lessons\\Ch 10\\pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
You can try getting the full path to the file
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
pi_digits = os.path.join(dir_path, 'pi_digits.txt')
with open(pi_digits, r) as file_object:
print(file_object.read())
You might have to enable "Execute in file dir"
vscode setting

Opening .exe from .txt error

I'm currently creating a script that will simply open a program in the SAME directory as the script. I want to have a text file named "target.txt", and basically the script will read what's in "target.txt" and open a file based on its contents.
For example.. The text file will read "program.exe" inside, and the script will read that and open program.exe. The reason I'm doing this is to easily change the program the script opens without having to actually change whats inside.
The current script Im using for this is:
import subprocess
def openclient():
with open("target.txt", "rb") as f:
subprocess.call(f.read())
print '''Your file is opening'''
Its giving me an error saying it cannot find target.txt, even though I have it in the same directory. I have tried taking away the .txt, still nothing. This code actually worked before, however; it stopped working for some strange reason. I'm using PythonWin compiler instead of IDLE, I don't know if this is the reason.
There are two possible issues:
target.txt probably ends with a newline, which messes up subprocess.call()
If target.txt is not in the current directory, you can access the directory containing the currently executing Python file by parsing the magic variable __file__.
However, __file__ is set at script load time, and if the current directory is changed between loading the script and calling openclient(), the value of __file__ may be relative to the old current directory. So you have to save __file__ as an absolute path when the script is first read in, then use it later to access files in the same directory as the script.
This code works for me, with target.txt containing the string date to run the Unix date command:
#!/usr/bin/env python2.7
import os
import subprocess
def openclient(orig__file__=os.path.abspath(__file__)):
target = os.path.join(os.path.dirname(orig__file__), 'target.txt')
with open(target, "rb") as f:
subprocess.call(f.read().strip())
print '''Your file is opening'''
if __name__ == '__main__':
os.chdir('foo')
openclient()

Categories

Resources