I am having issues with opening an Excel file from Jupyter Notebooks on my Mac. I previously saved it to my cloud.
To create the Excel, I copy my df to Excel and save it. So far so good.
path = '/Users/username/name.xlsx'
writer = pd.ExcelWriter(path,
engine = 'xlsxwriter')
df.to_excel(writer, sheet_name = 'Sheet1')
writer.save()
writer.close()
When I then try to launch it, it won't work.
Here's my code:
import os
os.system("open -a '/Applications/Microsoft Excel.app' path")
All I get is Output 256 in my notebook and Excel won't open.
Would anyone know why?
You need to pass the Python string stored in path as a value into the shell system in a form it will use.
An option is to use f-strings to do that:
import os
path = '/Users/username/name.xlsx'
os.system(f"open -a '/Applications/Microsoft Excel.app' {path}")
Alternatively, you can drop use of os.system and use IPython/Jupyter's ability to run shell commands on a line in a cell where you start with an exclamation point. That has built in that it will pass in Python variables for bracketed items in the call to the shell.
So in your Jupyter cell, you put:
path = '/Users/username/name.xlsx'
!open -a '/Applications/Microsoft Excel.app' {path}
On my Mac, I was able to replace the equivalent of /Users/username with ~. And so path = '~/name.xlsx' also worked from in a Jupyter to trigger launching of the Excel application with the specified spreadsheet file open.
You were using the full path, and so I kept that in my examples.
You can also change the working directory inside the notebook using the magic command %cd. If you change the current working directory to the directory where the file to open resides, you can and then shorten the 'path' to just be the name of the file.
Have you tried this:
import os
os.system("start EXCEL.EXE path")
If that dosn't work try yo use this Use Python to launch Excel file
as help :)
Related
I'm working with Jupyter Lab on a Mac. I've been trying to change the working directory in a .ipynb script via os.chdir(), so I can use the code to iteratively process multiple files in the working directory.
Eventually, I would like to use os.listdir() to iterate through the files in the directory.
My laptop files show up properly in the menu on the left, but for some reason, the following code won't work:
# set working directory
os.chdir('C:/Users/glonati/Documents/2019-_UNB SJ/drone/programs_code/python')
path = os.getcwd()
It produces the error: FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/glonati/Documents/2019-_UNB SJ/drone/programs_code/python'
I've quadruple checked the path names and tried all combinations of '', "", as well as , \, and /.
I read that I should try modifying the jupyter config file. But when I download the file (via jupyter notebook --generate-config), the only lines in the file are:
c.NotebookApp.allow_credentials = False
c.NotebookApp.port = 8889
c.NotebookApp.password_required = True
There is no line for c.NotebookApp.notebook_dir = ''.
Unsure why I'm having so much trouble with this. Any insight would be greatly appreciated! Thanks ahead of time!
My question is I am unable to run a python file in VS Code terminal unless I specify the full path.
Whereas, when I see any python tutorial, only python filename is entered and it works.
Can somebody pls help me with this issue?
The files need to be in the same folder where you are operating / or have the other Python files.
You can use two ways for this:
first:
import os
pwd = os.getcwd()
# again, make sure you file is in the same directory.
the_file = (pwd + "\\filename.xlsx")
or Secondly,
#the below you can use wherever your file is and it will locate it.
# you specify the full path using pathlib.path and:
pathlib.path(directory here without the file itself).joinpath(file name here).
data = pd.read_excel("ETH-USD")
I continually receive an error message informing me that the file cannot be found
this is despite the fact that
1: my directory has been changed within to Python to the same address as the folder where the excel file is stored
2: the file name is input exactly as displayed
Any ideas on why it is unable to find my file?
Is it possible that the excel file has an extension of .xlsx, but your file explorer is set to "hide file extensions"? Try:
data = pd.read_excel("ETH-USD.xlsx")
Or, see what's in the current directory by running:
import os
print(os.listdir())
A tip from the comments:
Windows tip too: hold Shift, right click the excel file and copy as path, then you can see its path (if you don't enable viewing file extensions in the file browser). –
creanion
Often when running python scripts from compilers the "working directory", or where you are running the script from doesn't match the location of your script, hence why I find it much more reliable to use this instead:
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
data = pd.read_excel(os.path.join(BASE_DIR,"ETH-USD")
To add, while I do not use Jupyter, in VSCode which I use, the working directory (which is where python looks for if you put a path in read_excel() but its not a full path) is often the current directory opened in there, so I expect a similar issue to be the reason for your issue.
I'm trying to run a python file through Jupyter Notebook. The first part of this file asks the user to import the data (.txt) file. Running it on a python IDE works well, however I want to make it work in Jupyter Notebook. I tried uploading the data beforehand, as seen in the image below.
It still doesn't detect the file nor reads the data. Any ideas on what else to try?
your jupyter has a directory where the notebooks are saved. If the file is not inside the notebook working directory (or a subtree of it) you can't access it, because it not exists. Your path C:\User\Downloads is obvisouly not this directory. Set your download directory to a jupyter directory, or move your text file. Check in jupyter what your working directory is.
Path errors are common in python. Especially if you often have to switch the programming language and then, few weeks later, back to python. I started to make me a helper method that I use in general in every new notebook and python application, to make not path errors. Maybe it helps you with correct working directory paths in the future.
import os
import sys
from pathlib import Path
def SetWorkingDir(abs_working_dir_path):
Debug = True
try:
if Debug:
print(f"[SetWorkingDir] Initial working directory: {os.getcwd()}", flush=True)
RootDir = False
if RootDir:
root_dir = os.path.dirname(os.path.realpath(__file__))
if Debug:
print(f"[SetWorkingDir] Local dir: {root_dir}", flush=True)
if (os.getcwd() != abs_working_dir_path):
os.chdir(abs_working_dir_path)
if Debug:
print(f"[SetWorkingDir] Working directory changed to: {os.getcwd()}", flush=True)
else:
if Debug:
print(f"[SetWorkingDir] Working directory unchanged at: {os.getcwd()}", flush=True)
return os.getcwd()
except Exception as ex:
print(f"\n[SetWorkingDir] Exception:"
f"\n{'Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(ex).__name__, ex}\n", flush=True)
And then all further paths relative to youur so set working directory (to make sure that your code also runs on other systems thans yours. Also use os.sep instead of \ as path seperator.)
best greetings
I would like to do a very simple thing but I am quite lost.
I am using a program called Blender and I want to write a script in python which open a .blend file but using the blender.app which is located in the same folder with the blend file, not with the blender.app which is located in Applications. (using Macosx)
So I was thinking that this should do the job...but instead it opens blender twice...
import os
path = os.getcwd()
print(path)
os.system("cd path/")
os.system("open blender.app Import_mhx.blend")
I also tried this one
import os
path = os.getcwd()
print(path)
os.system("cd path/")
os.system("open Import_mhx.blend")
but unfortunately it opens the .blend file with the default blender.app which is located in Applications...
any idea?
This cannot work since the system command gets executed in a subshell, and the chdir is only valid for that subshell. Replace the command by
os.system("open -a path/blender.app Import_mhx.blend")
or (much better)
subprocess.check_call(["open", "-a", os.path.join(path, "blender.app"),
"Import_mhx.blend"])
Have you tried telling the open command to open it WITH a specific application?
open -a /path/to/blender.app /path/to/Import_mhx.blend
Your first attempt was on the right track but you were really telling open to just open two different things. Not one with the other.