英文:
Someone else is working in "path" right now excel after saving it on a shared drive in python using to_excel
问题
我有一个Python脚本用于读取、修改和保存一个包含多个工作表的Excel文件,它按预期工作。该文件保存在共享驱动器上。
我的保存函数如下所示:
def save_xls(dict_df, path):
writer = ExcelWriter(path)
for key in dict_df:
dict_df[key].to_excel(writer, key, index=False)
writer.close()
然而,当我手动打开Excel并尝试更改其中的值时,我收到以下错误消息:现在有其他人正在"路径"上工作。请稍后再试。
我可以重新运行代码,这将覆盖Excel文件。
Pandas版本:1.5.3
Python版本:3.9
谢谢
我在线上查找过,但不幸的是没有找到解决我的问题的方法。
英文:
I have a python script reading, modifying and saving an excel file with several sheets -which works as expected. The file is saved on a shared drive.
My save function looks as follow:
def save_xls(dict_df, path):
writer = ExcelWriter(path)
for key in dict_df:
dict_df[key].to_excel(writer, key,index=False)
writer.close()
However when I open the excel manually and would like to change a value in it I receive the following error message: Someone else is working in "path" right now. Please try again later.
I can re run the code, which will overwrite the excel.
Pandas: 1.5.3
Python 3.9
Thank you
I read online but unforunately was not able to find a solution to my problem
答案1
得分: 1
错误消息表明Excel文件当前被另一个用户或进程锁定,阻止您对其进行更改。在您的情况下,锁定它以进行编辑的进程可能是您用来运行代码的编辑器(如VSC或Jupyter Notebook)。
为了避免这种情况,使用with
语句而不是writer
和writer.close()
:
import pandas as pd
def save_xls(dict_df, path):
with pd.ExcelWriter(path) as writer:
for key in dict_df:
dict_df[key].to_excel(writer, sheet_name=key, index=False)
# 使用这些示例进行测试
df1 = pd.DataFrame({'Column1': [1, 2, 3], 'Column2': [4, 5, 6]})
df2 = pd.DataFrame({'Column3': ['A', 'B', 'C'], 'Column4': ['D', 'E', 'F']})
dict_df = {'Sheet1': df1, 'Sheet2': df2}
save_xls(dict_df, 'C:\\Users\\admin\\OneDrive\\Documents\\my_file.xlsx')
完成后,您可以自由打开'my_file.xlsx'进行编辑和保存,而不会被锁定。
英文:
The error message you're encountering indicates that the Excel file is currently locked by another user or process, preventing you from making changes to it. In your case, the process that locks it for editing could be the editor you're using to run the code (such as VSC or Jupyter Notebook).
To avoid this, use the with
statement instead of writer
and writer.close()
:
import pandas as pd
def save_xls(dict_df, path):
with pd.ExcelWriter(path) as writer:
for key in dict_df:
dict_df[key].to_excel(writer, sheet_name=key, index=False)
#test with these examples
df1 = pd.DataFrame({'Column1': [1, 2, 3], 'Column2': [4, 5, 6]})
df2 = pd.DataFrame({'Column3': ['A', 'B', 'C'], 'Column4': ['D', 'E', 'F']})
dict_df = {'Sheet1': df1, 'Sheet2': df2}
save_xls(dict_df, 'C:\\Users\\admin\\OneDrive\\Documents\\my_file.xlsx')
After this, you're able to open the 'my_file.xlsx' to edit and save freely without being locked.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论