Python中自动关闭已打开文件脚本

检测指定位置的excel是否为打开状态,若是打开状态,强制保存并关闭,若是关闭状态,不做处理的逻辑

import psutil
import os
import win32com.client

def is_excel_open(file_path):
    for process in psutil.process_iter(['pid', 'name']):
        if "EXCEL.EXE" in process.info['name']:
            try:
                for file in process.open_files():
                    if os.path.abspath(file_path) == os.path.abspath(file.path):
                        return True
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass
    return False

def save_and_close_excel(file_path):
    try:
        excel = win32com.client.Dispatch("Excel.Application")
        excel.Visible = False
        workbook = excel.Workbooks.Open(os.path.abspath(file_path))
        workbook.Save()
        workbook.Close()
        excel.Quit()
    except Exception as e:
        print(f"Error while saving and closing Excel: {e}")

def process_excel_file(file_path):
    if is_excel_open(file_path):
        print(f"Excel file {file_path} is open. Saving and closing.")
        save_and_close_excel(file_path)
    else:
        print(f"Excel file {file_path} is closed. No action needed.")

# 示例用法
excel_file_path = "path/to/your/excel/file.xlsx"
process_excel_file(excel_file_path)

这个示例中,is_excel_open 函数用于检测指定位置的 Excel 文件是否被打开。如果文件被打开,save_and_close_excel 函数将使用 win32com.client 来打开文件、保存并关闭。在实际使用中,请确保你已经安装了 psutil 和 pywin32:

pip install psutil pywin32

你可能感兴趣的:(Python,python,开发语言,前端)