1

I'm trying to open a excel so it is displayed visibly.

I am using:

import subprocess
subprocess.check_call(['open', '-a', 'C:\\1\\2\\22.xlsx'])

https://ibb.co/eOhY4b

Sorry if this is obvious but I keep getting this error message. AS far as I can tell the file is located there.

FileNotFoundError: [WinError 2] The system cannot find the file specified
  • try `import os` and use `os.path.join('C:', '1', '2', '22.xlsx')` as your path argument, instead of formatting in manually. – jo9k Dec 06 '17 at 11:58
  • @jo9k Strange, I'm on windows 10 and this does nothing for me. I did find work around though. –  Dec 06 '17 at 12:01

2 Answers2

3

Not sure why

import os
os.path.join('C:', '1', '2', '22.xlsx')

Did not work. I think it worked but there was no visible excel.

Anyway, this works

xl=win32com.client.Dispatch("Excel.Application")
xl.Visible = True

xl.Workbooks.Open("C:\\1\\2\\22.xlsx")
3

it didn't work just because open isn't a known command name (this is an action in the windows registry, nothing more). The subprocess error message:

FileNotFoundError: [WinError 2] The system cannot find the file specified

has only one meaning: the executable could not be found. It doesn't (and cannot) check the parameters to see if they're valid filepaths so don't look in that direction (and yes, it's a pity that the message is generic and doesn't say exactly which file could not be found, that a known windows issue)

That would work:

import os
os.startfile(r'C:\1\2\22.xlsx')

os.startfile tries to perform the same thing as when you're clicking on the file in windows explorer.

This solution has the advantage not to depend on win32com.

Aside/discussed in comments: os.path.join('C:', '1', '2', '22.xlsx') doesn't work because it doesn't add the backslash after the drive colon (and for a "good" reason (well a good reason windows-wise): Python os.path.join on Windows).

>>> os.path.join('C:', '1', '2', '22.xlsx')
'C:1\\2\\22.xlsx'  # wrong

a clean way to do it:

>>> os.path.join('C:', os.sep,'1' , '2', '22.xlsx')
'C:\\1\\2\\22.xlsx'
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219