我想写文本文件而不关闭,因为我不知道我会停止什么,我会解释漏洞问题
我创建了一个名为resume.txt
的文本,因此在我的项目中的每个特定进程之后它将覆盖resume.txt
,所以每次我的项目启动它都会检查该文件以了解最后的进程,所以我的每次写作后我都要关闭以应用它,我真的不认为这是好的我认为有更好的解决方案
此代码无效
wr = open('resume.txt','w')
login(usr,pas)
wr.write('login')
post(msg,con)
wr.write('post')
..so on
问题是如何在不关闭的情况下编写,我不能在最后写wr.close
,因为它可能被用户终止或连接超时..等等
答案 0 :(得分:6)
不确定这是否适用于您的代码,但是在with
块中包装呢?
with open('resume.txt','w') as wr:
login(usr,pas)
wr.write('login')
# This is hacky, but it will go to the beginning
# of the file and then erase (truncate) it
wr.seek(0)
# I think you wanted to do this after you tried an action,
# but you can move it to wherever you want
post(msg,con)
wr.truncate()
wr.write('post')
这将确保文件在出错时关闭。如果要关闭文件,只需在与with
相同的级别上启动下一个代码:
with open('resume.txt','w') as wr:
login(usr,pas)
wr.write('login')
wr.seek(0)
post(msg,con)
wr.truncate()
wr.write('post')
# wr.seek(0) ...
# Next steps...
我还建议您查看logging模块,看看是否可以达到您想要的效果。
答案 1 :(得分:3)
首先,我要感谢tMC
解决方案是
wr = open('resume.txt','w')
login(usr,pas)
wr.write('login')
wr.flush()
post(msg,con)
wr.seek(0)
wr.write('post')
wr.flush()
我使用flush()
来编写和应用,seek(0)
用于覆盖
答案 2 :(得分:-1)
试试the with statement。理解有点复杂,但应该做到这一点。