我使用一个显式命名的文件作为临时文件。为了确保正确删除文件,我不得不为open()创建一个包装类。在
这似乎有用,但是
A]安全吗?在
有更好的办法吗?在
import os
string1 = """1. text line
2. text line
3. text line
4. text line
5. text line
"""
class tempOpen():
def __init__(self, _stringArg1, _stringArg2):
self.arg1=_stringArg1
self.arg2=_stringArg2
def __enter__(self):
self.f= open(self.arg1, self.arg2)
return self.f
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
self.f.close()
os.remove(self.arg1)
if __name__ == '__main__':
with tempOpen('tempfile.txt', 'w+') as fileHandel:
fileHandel.write(string1)
fileHandel.seek(0)
c = fileHandel.readlines()
print c
供参考:我不能用tempfile.NamedTemporaryFile有很多原因
我想您可以用
contextlib.contextmanager
来简化一下:有两种不同的错误需要处理:创建文件的错误和写入文件的错误。在
相关问题 更多 >
编程相关推荐