[python] If the Excel file is not closed, this error will be reported during openpyxl operation: PermissionError: [Errno 13] Permission denied: 'output.xls

need:

If the Excel file is not closed, this error will be reported during openpyxl operation: PermissionError: [Errno 13] Permission denied: 'output.xlsx', how can I detect whether it is closed, and let it close by itself? Code implementation

Analysis and solution

If the Excel file is already opened and in use by another program, we cannot use openpyxlthe module to read or write the file content. In order to avoid PermissionErrorthe exception , we can use try-exceptthe statement to catch the exception and close the Excel file when an exception occurs.

Here is a function that detects if an Excel file is opened by another program, and closes the file if it is in use:

import psutil
import os

def close_excel_file(file_path):
    for proc in psutil.process_iter():
        try:
            for item in proc.open_files():
                if item.path == os.path.abspath(file_path):
                    proc.kill()
        except:
            pass

In this function, we use psutilthe module to obtain the list of currently running processes, and then traverse the open file list of each process, and if the specified Excel file is found, proc.kill()the process is closed through the method.

In the main program, we can check whether the Excel file is already opened by another program before opening it. Closes the file if it is already open. Here is a complete code example:

import psutil
import os
from openpyxl import Workbook

# 检测 Excel 文件是否被其他程序打开并关闭文件
def close_excel_file(file_path):
    for proc in psutil.process_iter():
        try:
            for item in proc.open_files():
                if item.path == os.path.abspath(file_path):
                    proc.kill()
        except:
            pass

# 创建 Excel 文件
def create_excel_file():
    file_path = "output.xlsx"
    try:
        # 检查 Excel 文件是否已经被打开,如果是则关闭文件
        close_excel_file(file_path)
        # 创建工作簿
        wb = Workbook()
        # 选择第一个工作表
        ws = wb.active
        # 写入数据...
        # 保存文件
        wb.save(filename=file_path)
    except Exception as e:
        print("Error:", e)

# 测试代码
create_excel_file()

In this example, we first define a close_excel_filefunction to detect whether the Excel file is opened by another program, and close the file if it is already opened. Then, in create_excel_filethe function , we use try-exceptthe statement to catch PermissionErrorthe exception , and call close_excel_filethe function to close the file. Finally, we can call create_excel_filethe function to test the code.

Guess you like

Origin blog.csdn.net/qq_41604569/article/details/130586783