2

My code was working yesterday but today when I tried running it again it threw me an error and I've try to figure this out but I couldn't. Hope you can help me out here. Thanks much!

import fnmatch
import os
import scipy as s
import pandas as pd
import win32com.client as win32 

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.xlsx'):
    print(file)
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(file)
    excel.Visible = False
    excel.DisplayAlerts = False
    wb.DoNotPromptForConvert = True
    wb.CheckCompatibility = False

    ws = wb.Worksheets('Exec Summary')
    ws.Activate
    canvas = ws.Shapes

    for shp in canvas:
        if shp.TextFrame.Characters:
            print("Comments Found")
            print(shp.TextFrame2.TextRange)
            break
            wb.Close(True)

And this is the error the system threw:

---> 11 wb = excel.Workbooks.Open(file)

com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we couldn't find ZPC.xlsx. Is it possible it was moved, renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)

I have checked and confirm that the file is already in the directory. Have you guys encountered this before?

knl
  • 969
  • 11
  • 35

2 Answers2

1

Can you try doing a print of your file and see what comes up?

What is likely happening here is that you are not indicating the directory path correctly in os.listdir('.').
os.listdir('.') will check the default directory in which the python script you are running is located in.
If it is the same folder, it will work.
But if it is not, you have to specifically include the exact path of the folder. Example of how your exact filepath should look like:

filepath = r'C:\Users\yournamehere\Desktop\yourfolderhere\\' + 'ZPC.xlsx'  

Example of how your os.listdir should look like:

dirpath = r'C:\Users\yournamehere\Desktop\yourfolderhere\\'  
for file in os.listdir(dirpath):  
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(dirpath + file)

Also, if you wish to have a more elegant way of joining dirpath and file
You can use

os.path.join(dirpath, file)
ycx
  • 3,155
  • 3
  • 14
  • 26
  • Hey @ycx, thanks for commenting. I have checked that the file is in the same folder and when I do a print of files, the file does actually come up. Pretty strange that when I use Open(file), it says the file is possibly renamed, moved, etc. – knl Dec 16 '18 at 05:29
  • @Kelvin, use the `wb = excel.Workbooks.Open(dirpath + file)` code I've included in my answer. You will eliminate ambiguity that way. Let me know if it works – ycx Dec 16 '18 at 05:32
0

I know it might be too late to answer this, but try using

"excel.Visible = True" before using wb = excel.Workbooks.Open(dirpath + file).

DK_07
  • 1
  • 3