简体   繁体   English

在python中关闭时写作

[英]writing without closing in python

i want to write to text file without closing because i don't know what i'll stop close,i'll explain the hole issue 我想在不关闭的情况下写入文本文件,因为我不知道要停止关闭什么,我将解释漏洞

i've create text called resume.txt , so after each specific processes in my project it will overwrite in resume.txt so every time my project start it will check that file to know the last processes so my issue after each writing i have to close to apply it and i don't really think this is good i think there is better solution 我已经创建了名为resume.txt文本,因此在项目中的每个特定处理之后,它将覆盖resume.txt因此,每次我的项目启动时,它将检查该文件以了解最后一个处理,因此每次写后我的问题都必须接近应用它,我真的不认为这很好,我认为有更好的解决方案

this code will not work 此代码将不起作用

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

the issue is how to write without closing , i can't write the wr.close at the end because it might be terminated by the user or connection time out .. etc 问题是如何在不关闭的情况下写,我无法在最后写wr.close ,因为它可能会被用户终止或连接超时..等

Not sure if this applies to your code, but what about wrapping in a with block? 不知道这是否适用于您的代码,但是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')

This will ensure that the file is closed on error. 这样可以确保错误关闭文件。 When you want to close the file, just start your next code on the same level as with with : 当您要关闭文件时,只需在与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...

I would also recommend checking out the logging module to see if that can accomplish what you want. 我还建议您检出日志记录模块,看看是否可以完成您想要的工作。

first of all i'd like to thank tMC 首先,我要感谢tMC

the solution is 解决方案是

wr = open('resume.txt','w')
login(usr,pas)
wr.write('login')
wr.flush()
post(msg,con)
wr.seek(0)
wr.write('post')
wr.flush()

i've used flush() to write and apply and seek(0) for overwriting 我已经使用flush()编写并应用和seek(0)进行覆盖

Try the with statement . 尝试with语句 A little comlicated to understand, but should do exactly this. 有点复杂的理解,但是应该做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM