2

I am trying to open an excel document in the same folder as the python file using pywin32, but when I put in the file path by using the code below it gives me an error as if I input two backslashes rather than one

Both the python file and the excel file are in the same folder and are the only files in that folder.

the code:

file = r'\SeniorCadets.xlsm'
wb = xlApp.Workbooks.Open(file)

the error: " Sorry, we couldn't find \\SeniorCadets.xlsx. Is it possible it was moved, renamed or deleted?"

Alternatively, if I input just the name of the file, it also cannot find it

if I don't add a backslash: Sorry, we couldn't find SeniorCadets.xlsm. Is it possible it was moved, renamed or deleted?

The error only occurs with the xlApp.Workbooks.Open if I just print(file) it works fine

UPDATE: Below is all of the code up to the error as it stands now. The excel document is alone in a folder with the python file, it doesn't find the document even if it is just the name "SeniorCadets.xlsx" If the r is removed r"\SeniorCadets". To remove the r from the equation I have also tried both "\SeniorCadets" and "\\SeniorCadets" an extra \ always seems to appear in the error message

import os
import win32com.client as win32
from array import *
##Setup Outlook
olApp = win32.Dispatch('Outlook.Application')
olNS = olApp.GetNameSpace('MAPI')

##Setup Excel
os.chdir(r"fullFilePath")
xlApp = win32.Dispatch('Excel.Application')
xlApp.Visible = True
file = "SeniorCadets.xlsx"
wb = xlApp.Workbooks.Open(file)

EDITED WITH ANSWER FOR USER AS POST HAS BEEN CLOSED you need to use full path of the file rather than just its name eventhough file is in the same folder. One way to get full path without getting lost into backslahes is to use os.path libs:

import win32com.client as win32
from os.path import (dirname, abspath,
                     join)

##Setup Excel
xlApp = win32.Dispatch('Excel.Application')

# find the full path of the current py file sitting with your Excel 
# file and get its directory
root_dir = dirname(abspath(__file__))

file = "my_file_name.xlsm"

# build the full path of the file 
full_path = join(root_dir, file)

print(full_path)

wb = xlApp.Workbooks.Open(full_path)

xlApp.Visible = True
Je Je
  • 508
  • 2
  • 8
  • 23
Alexander
  • 21
  • 4
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/248359/discussion-on-question-by-alexander-pywin32-cannot-find-excel-file-no-matter-how). – Samuel Liew Sep 27 '22 at 06:09

0 Answers0