【问题标题】:"PermissionError: [Errno 13] Permission denied" when saving to an Excel-file using pandas使用 pandas 保存到 Excel 文件时出现“PermissionError:[Errno 13] Permission denied”
【发布时间】:2020-11-09 08:08:13
【问题描述】:

我正在尝试将数据从现有 Excel 文件“file1”加载到 panda 数据框,对其进行一些修改,然后将数据框导出到 相同的新工作表中工作簿(“file1”)。当“file1”关闭时,我的代码工作正常,但如果我在运行代码的同时在 Excel 中打开文件,我会收到错误:PermissionError: [Errno 13] Permission denied .这里有什么问题? Python 是否无法保存同时在 Excel 中打开的工作簿,或者这里有什么解决方法?

这是我的代码:

import pandas as pd
from openpyxl import load_workbook
 
#Read the input data to a panda dataframe       
df = pd.read_excel(workbook_path, sheet_name = 'input_data')

---Do stuff to the dataframe--

#Access the existing excel-file
workbook = load_workbook(workbook_path) 

#Create a writer-object   
writer = pd.ExcelWriter(workbook_path, engine = 'openpyxl')
writer.book = workbook

#Create a new sheet called "Results"
df.to_excel(writer,sheet_name = 'Results')

#Save the workbook
writer.save()
writer.close()

这是错误的完整输出:

【问题讨论】:

  • 没有。 Excel 对文件具有排他锁,不允许对其进行修改。这是标准功能,任何曾经处理过共享网络驱动器上文件的人都会证明这一点。 “好的 - 谁打开了 'foo.xls'?”

标签: python excel pandas openpyxl


【解决方案1】:

在 Excel 中打开文件时,会阻止来自其他应用程序的写入访问,以保持打开文件中的数据完整性。这意味着您应该只能获得只读访问权限。这不是 Python 特有的。

对于某些用例,可能有一种解决方法,可让您通过链接的 CSV 添加数据(有关详细信息,请参阅 Is it possible to write to an existing Excel file when it is **open** on the desktop?)。

【讨论】:

    猜你喜欢
    • 2017-02-12
    • 1970-01-01
    • 2019-07-31
    • 2016-08-17
    • 2020-07-29
    • 2019-11-27
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多