Opening/running Excel file from python

后端 未结 2 1612
予麋鹿
予麋鹿 2021-01-14 17:24

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

相关标签:
2条回答
  • 2021-01-14 17:47

    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 :)
    0 讨论(0)
  • 2021-01-14 17:49

    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!

    0 讨论(0)
提交回复
热议问题