为什么我在尝试使用 openpyxl python 读取单元格值时得到 "Permission denied error"?

Why am I getting a "Permission denied error" while trying to read a cell value using openpyxl python?

错误:

self.fp = io.open(文件,文件模式) PermissionError:[Errno 13] 权限被拒绝:'D:\gst_filer\invoice_data\jan\~$Jan05 Miracle gurukrupa.xlsx'

代码:

wb = openpyxl.load_workbook(filename=os.path.abspath(file), read_only=True)
ws = wb.active
cell_val = ws.cell(row=6,column=2)
print(cell_val)

您没有使用 with 语句并且没有 close() 语句所以如果这不是您第一次使用 运行 代码,您可能没有'未正确关闭文件,它仍位于内存中并阻止访问。

尝试关闭 Python 并重新启动并修改您的代码:

with openpyxl.load_workbook(filename=os.path.abspath(file), read_only=True) as wb:
    ws = wb.active
    cell_val = ws.cell(row=6,column=2)
    print(cell_val)

并尝试在 reading/writing 数据 from/to 文件时使用上下文管理器。

加上with statement的答案(非常好):

elf.fp = io.open(file, filemode) PermissionError: [Errno 13] Permission denied: 
'D:\gst_filer\invoice_data\jan\~$Jan05 Miracle gurukrupa.xlsx'

确保您的文件不是 used by another process,例如 excel app 或其他 program that reads .xlsx