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文件同一个目录下的另一个文件夹,就成功了。