4

I need to start excel and open a file directly from python. Currently I am using:

import os
os.system('start excel.exe file.xls')

However I do not get desired result. I want to open a file from local destination (file is in the same folder with program), but this code open's the file with same name in my home (user) directory and not from my program directory.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Domagoj
  • 1,674
  • 2
  • 16
  • 27
  • have you tried `os.curdir`? – gefei Dec 05 '12 at 10:25
  • Not a good way to do this. What is your use case? – Abhijit Dec 05 '12 at 10:27
  • 1
    @Abhijit: Why is it not good way to do this? It is standard way of starting applications in Windows. – Jan Hudec Dec 05 '12 at 10:27
  • @JanHudec: Because the implementation calls the standard C Sytem function call which has the same limitation. Rather one should use subprocess. Refer the section [Replacing os.system]( http://docs.python.org/2/library/subprocess.html#replacing-os-system). Also note, there are other elegant ways like win32com.client. If the requirement is only to edit an excel, there are other great libraries like openpyxl or xlrd/xlwt – Abhijit Dec 05 '12 at 10:33
  • @Abhijit: But you didn't say which limitation you mean. – Jan Hudec Dec 05 '12 at 12:16
  • 1
    A small aside: You can shorten this to "start file.xls" and Windows will automatically pick the correct program to launch. – Deestan Dec 05 '12 at 12:21

2 Answers2

5

The problem is that the directory where the program is located is not used. The current working directory is. So you have to find out which directory your program is located in, which python conveniently prepared for you in:

sys.path[0]

and either change directory to it:

os.chdir(sys.path[0])

or give full path for the file you want to open

os.system('start excel.exe "%s\\file.xls"' % (sys.path[0], ))

Note, that while Windows generally accept forward slash as directory separator, the command shell (cmd.exe) does not, so backslash has to be used here. start is Windows-specific, so it's not big problem to hardcode it here. More importantly note that Windows don't allow " in file-names, so the quoting here is actually going to work (quoting is needed, because the path is quite likely to contain space on Windows), but it's bad idea to quote like this in general!

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
  • `start` in that intent is Windows specific - however, on some linux distro's, it's also a wrapper around `initctl` :) – Jon Clements Dec 05 '12 at 10:35
2

You can also define the directory, where the python should operate.

import os

os.chdir('C:\\my_folder\\subfolder')

os.system('start excel.exe my_workbook.xlsx')
  1. Don't forget to use backslashes in your path and there must be two of them everytime.
  2. my_workbook.xlxs - here will be the name of your file
  3. That file must be in that folder :)
Vaclav Vlcek
  • 317
  • 1
  • 6
  • 17