Python执行顺序(文件写入和读取)

2024-04-25 13:08:52 发布

您现在位置:Python中文网/ 问答频道 /正文

有什么理由

out = open("tmp.gp",'w')
out.write('plot sin(x)')
out.close
system('gnuplot -persist tmp.gp')

不起作用,但这些(下面)能起作用吗?你知道吗

system('gnuplot -persist tmp.gp')
out = open("tmp.gp",'w')
out.write('plot sin(x)')
out.close

请注意,我没有删除tmp.gp公司在程序运行期间,那么在这两种情况下,文件都存在,并且在执行这些行之前包含命令“plot sin(x)”(因为文件存在于上一次运行中)?你知道吗

我唯一的猜测是,这可能是一个竞争条件,但把一个原始的输入()消磨时间没有帮助(见下文)。谢谢你的帮助!你知道吗

out = open("tmp.gp",'w')
out.write('plot sin(x)')
out.close
raw_input()
system('gnuplot -persist tmp.gp')

Tags: 文件程序运行closeplot公司sinopenout
2条回答

正如其他人提到的,您没有正确地使用close()。在处理文件时,还应使用statment:

with open("tmp.gp",'w') as out:
    out.write('plot sin(x)')
    out.close()

这样即使您自己不关闭文件,或者写入文件会引起错误,文件仍然会关闭。你知道吗

这是因为您实际上没有调用close函数,所以将out.close更改为out.close()。函数调用需要()才能被调用。你知道吗

相关问题 更多 >