需求:
Excel文件如果没有关掉,openpyxl操作的时候会有这个报错:PermissionError: [Errno 13] Permission denied: ‘output.xlsx’,怎么能检测有没有关掉,并让其自己关掉呢,代码实现
分析与解决
如果 Excel 文件已经被其他程序打开并且正在使用,我们无法使用 openpyxl
模块读取或写入文件内容。为了避免出现 PermissionError
异常,我们可以使用 try-except
语句捕获异常,并在发生异常时关闭 Excel 文件。
以下是一个检测 Excel 文件是否被其他程序打开的函数,如果文件正在使用,则关闭文件:
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
在这个函数中,我们使用 psutil
模块来获取当前正在运行的进程列表,然后遍历每个进程的打开文件列表,如果找到了指定的 Excel 文件,则通过 proc.kill()
方法关闭该进程。
在主程序中,我们可以在打开 Excel 文件之前检查它是否已经被其他程序打开。如果文件已经被打开,则关闭文件。以下是一个完整的代码示例:
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()
在这个示例中,我们首先定义了一个 close_excel_file
函数来检测 Excel 文件是否被其他程序打开,并在文件已经被打开时关闭文件。然后,在 create_excel_file
函数中,我们使用 try-except
语句来捕获 PermissionError
异常,并调用 close_excel_file
函数来关闭文件。最后,我们可以在主程序中调用 create_excel_file
函数来测试代码。