给定文件的路径,如何关闭在windows上使用python的excel应用程序中打开的特定csv文件?
发布时间:2022-04-01 11:48:08 220
相关标签: # node.js
我有一个将数据写入csv文件的脚本,但如果该csv文件处于打开状态(在Windows 10上的excel应用程序中),则会生成一个PermissionError。这是有道理的。
我希望能够捕获PermissionError,然后关闭该文件,特别是关闭Windows 10上excel应用程序中打开的一个csv文件。我不想关闭整个excel应用程序,而是确定特定的文件,然后关闭该文件,让excel中打开的任何其他文件保持不变。
我已经研究过使用subprocess来实现这一点,但我不清楚如何实现这一点。这似乎是最有可能的路线,除非有更好的路线可以推荐。
最终的代码如下所示:
import time
import pandas as pd
path_to_file = 'path/to/file.csv'
df = pd.DataFrame()
try:
df.to_csv(path_to_file) # file that is currently open
except PermissionError:
print('Shutting the Open File')
time.sleep(5)
shut_the_open_file(path_to_file) # need to figure out this code for closing the currently open file
df.to_csv(path_to_file)
谢谢
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报