检查文件是否在 Python 中打开 [英] check if a file is open in Python

查看:34
本文介绍了检查文件是否在 Python 中打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我写入了一个 excel 文件.写入后,用户可以通过打开文件来查看文件.但是如果用户在进一步写入之前忘记关闭文件,则会出现警告消息.所以我需要一种在写入过程之前检查这个文件是否打开的方法.你能给我提供一些 Python 代码来完成这个任务吗?

In my app, I write to an excel file. After writing, the user is able to view the file by opening it. But if the user forgets to close the file before any further writing, a warning message should appear. So I need a way to check this file is open before the writing process. Could you supply me with some python code to do this task?

推荐答案

我假设您正在写入文件,然后关闭它(以便用户可以在 Excel 中打开它),然后在重新打开它之前对于追加/写入操作,您想检查文件是否仍在 Excel 中打开?

I assume that you're writing to the file, then close it (so the user can open it in Excel), and then, before re-opening it for append/write operations, you want to check that the file isn't still open in Excel?

你可以这样做:

while True:   # repeat until the try statement succeeds
    try:
        myfile = open("myfile.csv", "r+") # or "a+", whatever you need
        break                             # exit the loop
    except IOError:
        input("Could not open file! Please close Excel. Press Enter to retry.")
        # restart the loop

with myfile:
    do_stuff()

这篇关于检查文件是否在 Python 中打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆