【Python报错:xlsx文件 PermissionError】xlsx文件的 [Errno 13] Permission denied: ‘C:/Data.xlsx‘

Traceback (most recent call last):
  File "c:\Users\EmailSender\EmailSender.py", line 93, in <module>
    df.to_excel(file_path, index=False)

             ^^^^^^^^^^^^^^^^^^^^^^^^^
PermissionError: [Errno 13] Permission denied: 'C:/Users/Desktop/SAP_Data/Data.xlsx'

在数据写入时,发生报错,如何解决?

- 在将email写入到xlsx文件时:运行到df.to_excel(file_path, index=False) 发生报错,具体代码如下:

    if prognose_date is not None and current_date > prognose_date:
        # Prepare email content
        subject = 'Greetings'
        body = f"""
Hallo {full_name}, nice to meet you
"""
        # Add email address and content to the lists
        emails.append(to_email)
        email_contents.append(body.strip())
        print("email_content", email_contents)
    else:
        # If no email content is generated, add an empty string
        emails.append('')
        email_contents.append('')

# Update the dataframe with new columns
df['Email'] = emails
df['Email_Content'] = email_contents

# Save the updated dataframe back to the Excel file
df.to_excel(file_path, index=False)

先讲讲这个error出现的可能原因:

核心原因是:

Python 脚本没有修改该文件所需的权限。

但该错误是由于多种原因产生的:

Excel 文件已打开了:

如果 Excel 文件已在另一个应用程序(例如 Microsoft Excel)中打开,则 Python 脚本无法修改该文件。在运行python前一定记得关闭 Excel 文件。

解决方案:运行python前,关闭 Excel 文件。

没有写入权限:

如果没有该文件或该文件所在目录的写入权限,则会遇到此错误。

解决方案: 使用管理员权限运行脚本:右键单击 Python 脚本或 Python 解释器(例如 IDLE、PyCharm 等),然后选择“以管理员身份运行”。

从受限位置运行脚本:

如果用户帐户没有写入权限的位置(例如系统目录)运行脚本,则可能会遇到此错误。

解决方案:更改工作目录:不要使用绝对文件路径(“C:/Users/Desktop/Data.xlsx”),而是用相对文件路径或将工作目录更改为具有写入权限的位置。可以使用 Python 中的 os.chdir() 函数更改工作目录。

import os

# Change the working directory to the desktop
os.chdir(os.path.expanduser('~/Desktop'))

# Use a relative file path
file_path = 'SAP_Data/Data.xlsx'

这三个方案都试了,都不起作用,最后将Excel文件移动到了和python文件同一个目录下的另一个文件夹,就成功了。

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值