【问题标题】:Read from excel file that is open in Python从 Python 中打开的 excel 文件中读取
【发布时间】:2019-11-08 05:44:42
【问题描述】:

我有一个脚本,每隔几个小时从 excel 文件中提取数据。但是,如果这些 excel 文件之一是打开的,我仍然希望能够从中读取。

在 python (openpyxl) 中尝试执行此操作时出现权限错误。

以下是我尝试过的。我想我可以捕获异常并创建一个我可以读取的文件的临时版本。

try:
    read_from = load_workbook(fileName)
except:
    tempFileName = "directory\\temp " + fileName + ".xlsx"
    open(tempFileName, 'wb').write(open(fileName, 'rb').read())
    read_from = load_workbook(tempFileName)

但是,即使这样,我也会收到以下错误:

----> 6         open(tempFileName, 'wb').write(open(fileName, 'rb').read())
  7         read_from = load_workbook(tempFileName)
  8     read_sheet = read_from.active

PermissionError: [Errno 13] Permission denied: 'directory\\testfile.xlsx'

【问题讨论】:

  • 我可以使用load_workbook 访问打开的Excel 文件,但不能使用open()。您使用的是哪个版本的 openpyxl 和 Excel?
  • 在打开的文件上使用read_from = load_workbook(fileName) 时遇到什么错误?
  • @Joe 我得到 PermissionError: [Errno 13] Permission denied for using load_workbook(fileName) on an open excel file。这适用于存储在 Onedrive 上的 office 365 excel 文件。关闭时,“read_from = load_workbook(fileName)”工作正常。
  • 嗯,那么我们有两种不同的情况。我有 Excel 2013,文件在本地硬盘上。对open()load_workbook()同样的原因失败。

标签: python file permissions copy


【解决方案1】:

我只是把你的代码写成

fh_in = open(fileName, 'rb')
fh_out = open(tempFileName, 'wb')

f_in_content = fh_in.read()
fh_out.write(f_in_content)

查看错误实际发生的位置。在我的情况下,这不是因为输入文件打开,而是输出文件。

读取文件工作正常,但是当我尝试将其写入目标文件时,它失败并显示PermissionError

【讨论】:

    【解决方案2】:

    通过命令行创建文件的临时副本,然后稍后删除临时文件似乎可以正常工作。

    try:
        read_from = load_workbook(fileName)
        delTempFileFlag = False
    except:
        print("file: ",item,"is open, so cannot be accessed")
        tempFileName = "directory\\temp " + fileName + ".xlsx"
        command = "xcopy \"" + fileName + "\" " + "\"" + tempFileName + "*\""
        os.system(command)
        print("Temporary copy of file created to work with")
        read_from = load_workbook(tempFileName)
        delTempFileFlag = True
    ...
    ...
    if delTempFileFlag == True:
        os.remove(tempFileName)
        delTempFileFlag = False
    

    【讨论】:

    • 注意:这是提问者作为问题的一部分发布的;我已将其移至社区 Wiki 答案
    猜你喜欢
    • 1970-01-01
    • 2014-05-30
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    相关资源
    最近更新 更多