我怎么能得到python3文件.关闭释放文件锁



Python3文件。close显然不能释放文件,所以Win7命令不能使用它。

即:

import os, time
hfile = "Positions.htm"
hf = open(hfile, "w")
hf.write(str(buf))
hf.close
time.sleep(2) # give it enough time to do the close
os.system(hfile) # run the html file in the default browser

这会导致Win7的错误消息,说它无法访问该文件,因为它目前正在使用中。但是,在python程序终止后,它很容易被访问。

是的,我知道这里也有人问过类似的问题,但我还没有看到有人给出一个笼统的答案。

您只是忘记调用close()

hf.close   # wrong
hf.close() # right

你可以看到hm.close只是给了你一个没有调用它的绑定方法:

>>> hm.close
<built-in method close of _io.TextIOWrapper object at 0x7ffe8ec74b40>

正如Padriac狡猾ham指出的那样,如果您只使用with语法,则不需要这样做:

with open(hfile, 'w') as hf:
    hf.write(str(buf))
# Automatically closed

最新更新