“另一个进程正在使用的文件”错误消息

时间:2014-07-27 07:37:55

标签: python file-io

是的,此主题还有许多其他问题。我查看过这些回复,但我没有看到任何可以提供有用解决方案的回复。

我的问题最简单:

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

我收到此错误消息:"该进程无法访问该文件,因为它正被另一个进程使用"。该程序中没有其他地方引用该文件。

没有其他进程正在使用它,因为我可以在没有任何其他程序错误的情况下访问它,即使我从python控制台运行os.system(file)也是如此。

使用解锁器没有意义,因为一旦我离开程序,我就可以在浏览器中打开html文件而不会受到系统的投诉。

看起来像是“关闭”。没有正确释放文件。

我一直以这种方式运行程序,除了需要1或2秒的延迟之外没有任何问题。

我在Win7上使用Python 3.4。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您没有致电close()。需要:

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

但是为了避免这样的问题,您应该使用上下文管理器:

import os, time
hfile = "Positions.htm"
with open(hfile, 'w') as hf:
    hf.write(str(buf))
os.system(hfile) # run the html file in the default browser

上下文管理器将自动处理文件的关闭。

相关问题