简体   繁体   中英

closing an excel file using python if file is already open

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

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 .

import xlwings as xw
try:
    book = xw.Book('export.xlsx')
    book.close()
except Exception as e:
    print(e)

This will close the workbook if it is open. You may need to let python wait for SAP to open the file so something like the following may be necessary prior to trying to close the workbook

import time
#wait for SAP to open file
time.sleep(3)

I can't help with the second part of your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM