如何检查文件是否已经打开(在同一过程中)
我想通过try catch构造来专门实现这一目标.
And I'd like to specifically achieve that with the try catch construct.
此相关问题建议我可以执行以下操作:
This related question suggests that I can do:
try:
open(fileName, 'wb+')
except:
print("File already opened!")
raise
但是,它对我不起作用.我可以多次打开同一个文件而没有任何问题:
However, it doesn't work me. I can open the same file multiple times without any problem:
fileObj1 = open(fileName, 'wb+')
fileObj2 = open(fileName, 'wb+')
是因为我有Python 3.5吗?还是因为我正在使用 Raspbian ?
Is it because I have Python 3.5? Or because I'm using Raspbian?
感谢您的帮助!
您打开相同的文件,但将它们分配给不同的变量.您应该做的是:
You open the same file but assign them to different variables. What you should do is:
fileobj=open(filename,"wb+")
if not fileobj.closed:
print("file is already opened")`
我正在用手机写字,因此样式可能不太好,但是您会明白这一点的.顺便说一句,.closed
仅检查文件是否已由相同的python进程打开.
I'm writing with my phone so the styling may not be good but you will get the point. By the way the .closed
only checks if the file has been opened by the same python process.