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

查看:149
本文介绍了检查一个文件是否在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 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?

这是你应该怎么做那个:

This is how you should do that:

try:
    myfile = open("myfile.csv", "r+") # or "a+", whatever you need
except IOError:
    print "Could not open file! Please close Excel!"

with myfile:
    do_stuff()

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

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