我正在使用一个明确命名的文件作为临时文件。为了确保我正确删除文件,我必须为 open() 创建一个包装类。
这似乎可行,但是
A] 安全吗?
B] 有没有更好的方法?
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
做一些更简单的事情:
from contextlib import contextmanager
@contextmanager
def tempOpen( path, mode ):
# if this fails there is nothing left to do anyways
file = open(path, mode)
try:
yield file
finally:
file.close()
os.remove(path)
有两种错误需要以不同的方式处理:创建文件错误和写入文件错误。
关于Python 使用 'with' 在使用后删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5019209/