closing an excel file using python if file is already open

Viewed 16167

Hi I am new to python scripting, I wrote a code for SAP automation but at last excel file open so I want to close that file.

I need a help regarding code to check if specific excel file is already open, if open than closing the same using python.

Thanks for help in advance.

I am using below code:

        with open('C:\\Users\\Xyz\\AppData\\Local\\Temp\\export.XLSX', 'r') as f:
        f.close()

Also if someone can hep me converting VBA function in python and can tell me how to call the same.

Function WKopen(wb As String) As Boolean
On Error Resume Next
WKopen= Len(Workbooks(wb).Name)
End Function

Sub BK_Close()
On Error Resume Next
If WkOpen("Export_Download.XLSX") Then
Workbooks("Export_Download.xlsx").Close savechanges:=False
Else
End If
End Sub
1 Answers

Ok. You have actually used two methods of closing a file together.

You should either use with which closes the file as soon as you come out of the with block.

Or

You can open your file without with like:

f = open('C:\\Users\\Xyz\\AppData\\Local\\Temp\\export.XLSX', 'r')

and then close using f.close().


Now, since, you are new, the best way to open Excel files on Python is to use pandas library's read_excel function.

So, the code will be:

import pandas as pd
pd.read_excel('C:\\Users\\Xyz\\AppData\\Local\\Temp\\export.XLSX')

Here's the documentation for it, if you need something more from this function, here.

Related