when i try
os.system("open " + 'myfile.xlsx')
i get the output '0'
similarly, trying
os.system("start excel.exe myfilepath")
gives the result 32512
I have imported os and system, and I'm on mac. How can I change this so it does actually launch that excel file? And out of curiosity, what do the numbers it prints out mean?
Thanks!
Just these two lines
import os
os.system("start EXCEL.EXE file.xlsx")
Provided that file.xlsx is in the current directory.
If you only want to open the excel application you could use subprocess:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])
You can also use os and open a specific file:
import os
os.system("open -a 'path/Microsoft Excel.app' 'path/file.xlsx'")
If you on other hand want to open an excel file within python and modify it there's a number of packages to use as xlsxwriter, xlutils and openpyxl where the latter is prefered by me.
Another note, if you're on mac the excel application isn't .exe
On Windows 10, this works for me:
import os
full_path_to_file = "C:\blah\blah\filename.xlsx"
os.system(full_path_to_file)
Copy-pasting any full path to a file in the command prompt (or passing it to os.system()) seems to work as long as you have permission to open the file.
I suppose this only works when Excel is selected as default application for the .xlsx extention.
I don't know about Mac OS, but if Windows Operating System is the case and provided the Microsoft Windows is properly installed, then consider using :
import os
os.system('start "excel" "C:\\path\\to\\myfile.xlsx"')
double-quotation is important for excel and C:\\path\\to\\myfile.xlsx ( where C just denotes the letter for the partition within the file system, might be replaced by D,E ..etc. ), and single-quotation is needed for the whole string within the os.system().
As in: How to open an Excel file with Python to display its content?
import os
file = "C:\\Documents\\file.xlsx"
os.startfile(file)
It opens the file with the default application.
If you want this to work with your most recent downloaded xlsx file, you can use the following:
import glob
import os
list_of_files = glob.glob('C:\\Downloads\\*.xlsx') *#note the .xlsx extension is needed to retrieve the last downloaded xlsx file.*
latest_file = max(list_of_files, key=os.path.getctime)
os.system(latest_file)
A minor improvement that handles spaces and explicitly uses Excel:
import os
file = "C:/Documents/file name with spaces.xlsx"
file_with_quotes = '"' + file + '"'
os.system('start "EXCEL.exe" {}'.format(file_with_quotes))
Related
I wrote a simple script that decodes and sorts my scans (*.pdf) into Sharepoint. Everything works on my home PC where I tested it, but on my work pc it doesn't want to work. I want to drag and drop the pdfs (multiple sometimes) onto the script.
I printed out the path the script gets when the drag and drop starts.
Example: 20 ENS 02 0052.pdf turns into 207D51~1.PDF
Because somehow drag and drop doesn't work on this pc I had to create a shortcut to the script and add 'python' before the text in the target of the shortcut. ( But it also wont work if I just pass the file in console as argument
My debug script:
import sys
from pathlib import Path
import os
file = os.path.basename(sys.argv[1])
print(file)
os.system('pause')
The part of the original script i can show:
import os
import sys
import getopt
import sqlite3
from pathlib import Path
for pdf in sys.argv[1:]:
# extract filename and
file = os.path.basename(pdf)
# remove extension from full path
filename = file[:-4]
print("File: ".format(file))
print("Filename: ".format(filename))
# just for debug script would continue here
os.system("pause")
exit()
I tried it using a test script for debugging and passing the file as argument in console instead of drag and drop, but the same error happens. Worked on my work pc (also newest working version of python3).
\parentDirectory
\subdr1
-testfile.txt
\subdr2
\childdir
-file.json
-file2.pickle
-fileOpener.py
I would like to read the file.json from fileOpener.py in Python using:
with open("./childdir/file.json", 'r') as f:
But I'm getting FileNotFoundError.
FileNotFoundError: [Errno 2] No such file or directory: './childdir/file.json'
Would anyone mind solving this issue? I'm using WINDOWS operating system.
If you run fileOpener.py within the subdir2 then all is well. The problem happens when you are not in subdir2. Here is the solution:
import pathlib
this_script = pathlib.Path(__file__)
json_path = this_script.parent / "childdir" / "file.json"
with open(json_path, 'r') as f:
...
Since pathlib is cross-platform, this code should work under Windows. I tested it under Mac and linux.
First of all which OS are you using ? since windows uses \ and UNIX based OSes use /
Bast approach would be to use path from os module like this:
import os
with open(os.path.join('childdir', 'file.json'), 'r')" as f:
# YOUR CODE
This is a better approach because it is platform independent since it creates the path appropriately based on the OS you are on.
This is because the file you want to open is in the subdirectory of your current working directory(where the python file is present).
You need to consider 2 things here,
Depends on the OS which you're using, it's either '/' for UNIX-based &
'' for Windows-based as separator in the file's path
we can either use the absolute path of the file and mode to open the file
or with the path sub-module of that os module.
# With absolute path in Windows
with open('F:\parentDirectory\subdr2\childdir\file.json', mode(r/a/w..)) as fl:
# logic
or
# with os.path submodule
import os
with open(os.path.join('childdir', 'file.json'), mode('r/w/a/..')) as fl:
# logic
I have a script to extract all the contents of an .exe file however, the register_archive_format and register_unpack_format functions don't seem to work as expected. Here's a short version of my script:
import os
import re
import py7zr
import wget
import shutil
import zipfile
versions = ["1.10", "2.0", "2.1pre"]
shutil.register_archive_format('exe', py7zr.pack_7zarchive, description="exe archive")
shutil.register_unpack_format('exe', ['.exe'], py7zr.unpack_7zarchive)
print("Supported formats:")
formats = shutil.get_unpack_formats()
print(formats, "\n")
with py7zr.SevenZipFile(f"C:/Users/Me/Documents/Builds/{version}/{filePath}", 'r') as zip_ref:
folderName = re.search("^([^_]+)(-installer)([^.]*)", fileNameOnly)
folderName = folderName[1] + folderName[3]
#zip_ref.extractall(f"C:/Users/Me/Documents/Builds/{version}/{folderName}")
shutil.unpack_archive(zip_ref, f"C:/Users/Me/Documents/Builds/{version}/{folderName}")
The code prints the list of supported formats from shutil.get_unpack_formats() and seems to correctly show the exe file registered. But when the code reaches the shutil.unpack_archive() function it throws py7zr.exceptions.Bad7zFile: not a 7z file.
Is there a step I'm missing in order to extract from an exe file? I know I can extract from the exe as I do that manually through the context menu of the exe file.
py7zr support only a 7z file that has an extension foo.7z (it is not mandatory) and the binary should be started with '7z' magic keyword.
You may want to extract a self extracting archive (https://en.wikipedia.org/wiki/Self-extracting_archive) which will start a magic bytes which indicate it as executable. It is not supported by the tool.
That is why py7zr say it is not a (plain) 7z file.
Please see details at https://py7zr.readthedocs.io/en/latest/py7zr.html
I am trying to use a script to open a file inside a network drive using python. The script is given below:
import os
import subprocess
file_path = r"O:\XXXX\test.xls"
subprocess.Popen(filepath, shell=True)
The network drive requires sign in but I always by default sign it the moment I on the computer. Also, using a os.listdir(folderpath) has no problem going into the network drive and listing all the files in the directory containing the file.
Tried some suggestions from similar posts but they don't work.
I am using Python 2.7, and Windows.
UPDATE:
No error was prompted after executing the script.
I am trying to open an Excel file. The script works to open Excel in other folders within the computer, but just not within the network drive.
Thanks to #J.F. Sebastian's suggestion. replacing subprocess.Popen(filepath, shell=True) with os.startfile(filepath) works.
I think this could help you
import subprocess
file_path = r"X:\dir\excelfile.xlsx"
#~ also this works
#~ file_path = r"\\server\dir\excelfile.xlsx"
subprocess.call(file_path,shell = True)
when i try
os.system("open " + 'myfile.xlsx')
i get the output '0'
similarly, trying
os.system("start excel.exe myfilepath")
gives the result 32512
I have imported os and system, and I'm on mac. How can I change this so it does actually launch that excel file? And out of curiosity, what do the numbers it prints out mean?
Thanks!
Just these two lines
import os
os.system("start EXCEL.EXE file.xlsx")
Provided that file.xlsx is in the current directory.
If you only want to open the excel application you could use subprocess:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])
You can also use os and open a specific file:
import os
os.system("open -a 'path/Microsoft Excel.app' 'path/file.xlsx'")
If you on other hand want to open an excel file within python and modify it there's a number of packages to use as xlsxwriter, xlutils and openpyxl where the latter is prefered by me.
Another note, if you're on mac the excel application isn't .exe
On Windows 10, this works for me:
import os
full_path_to_file = "C:\blah\blah\filename.xlsx"
os.system(full_path_to_file)
Copy-pasting any full path to a file in the command prompt (or passing it to os.system()) seems to work as long as you have permission to open the file.
I suppose this only works when Excel is selected as default application for the .xlsx extention.
I don't know about Mac OS, but if Windows Operating System is the case and provided the Microsoft Windows is properly installed, then consider using :
import os
os.system('start "excel" "C:\\path\\to\\myfile.xlsx"')
double-quotation is important for excel and C:\\path\\to\\myfile.xlsx ( where C just denotes the letter for the partition within the file system, might be replaced by D,E ..etc. ), and single-quotation is needed for the whole string within the os.system().
As in: How to open an Excel file with Python to display its content?
import os
file = "C:\\Documents\\file.xlsx"
os.startfile(file)
It opens the file with the default application.
If you want this to work with your most recent downloaded xlsx file, you can use the following:
import glob
import os
list_of_files = glob.glob('C:\\Downloads\\*.xlsx') *#note the .xlsx extension is needed to retrieve the last downloaded xlsx file.*
latest_file = max(list_of_files, key=os.path.getctime)
os.system(latest_file)
A minor improvement that handles spaces and explicitly uses Excel:
import os
file = "C:/Documents/file name with spaces.xlsx"
file_with_quotes = '"' + file + '"'
os.system('start "EXCEL.exe" {}'.format(file_with_quotes))