写作没有在python中关闭

Ham*_*daq -1 python io text overwrite python-2.7

我想写文本文件而不关闭,因为我不知道我会停止什么,我会解释漏洞问题

我已创建调用的文本resume.txt,因此在我的项目中的每个特定进程之后它将覆盖,resume.txt因此每次我的项目启动它都将检查该文件以了解最后的进程所以我的问题在每次编写后我必须关闭以应用它而我不要认为这很好,我认为有更好的解决方案

这段代码不起作用

wr = open('resume.txt','w')
login(usr,pas)
wr.write('login')
post(msg,con)
wr.write('post')
..so on 
Run Code Online (Sandbox Code Playgroud)

问题是如何在没有关闭的情况下编写,我不能wr.close在最后编写,因为它可能被用户终止或连接超时..等等

Roc*_*key 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')
Run Code Online (Sandbox Code Playgroud)

这将确保文件在出错时关闭.如果要关闭文件,只需在与以下相同的级别上启动下一个代码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...
Run Code Online (Sandbox Code Playgroud)

我还建议检查日志记录模块,看看它是否可以完成你想要的.