Reputation: 61
I am trying to create an application with python, that can open up several different file types on a desktop. One of the files that I am trying to open up is an Excel File. Searching through Stackoverflow I came up with the bit of code below however, it is not working. Can anyone help?
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 16:30:00) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import os
>>> os.startfile(dirpath + '\\' + 'C:\Users\kmoret\Desktop\THE PLAN_p.xlsm')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated
\UXXXXXXXX escape
>>>
Upvotes: 0
Views: 550
Reputation: 2865
"\" is a special character in Python. If you want to put "\" in a Python string you have to use "\\". Also, it's recommended to use os.path.join() to safely concat directories
import os
from sys import platform
def start_file(path: str):
"""Opens file with default app
Usage:
>>> start_file("my_file.xslx")
"""
if platform.startswith(("cywin", "win32")):
os.startfile(path)
elif platform.startswith("linux"):
os.system(f"xgd-open {os.path.abspath(path)}")
elif platform.startswith("darwin"):
os.system(f"open {os.path.abspath(path)}")
start_file("my_file.xlsx")
If you are going to join paths:
import os
path = os.path.join('C:','Users','kmoret','Desktop','THE PLAN_p.xlsm')
start_file(path)
If you already have the path defined:
import os
path = os.path.normpath('C:/Users/kmoret/Desktop/THE PLAN_p.xlsm')
start_file(path)
Upvotes: 3
Reputation: 45
I'm new to using python but from my research and testing I'm creating a script in python first to make the excel file. You can change the .xml
to any file type. .xml
just represents the excel version I have. You could replace it with .docx
to open a word file
#Creating the file
file=open("hiiiiiii.xml","w")
Then I opened the file using a simple script of os systems. I also put a while loop on it so whenever you close the excel file it opens again until you stop the script in python
#Opening the file
import os
while True:
os.system("hiiiiiii.xml")
Upvotes: 0