我正在生成以下NamedTemporaryFile-
## CONFIGURE DEPLOY.XPR
template = open(xprpath + xprtemplatefile, 'r')
joblist = open(joblistfilepath + joblistfilename, 'r')
temp = NamedTemporaryFile(delete=False)
data = template.read()
listjobs = joblist.read()
template.close()
joblist.close()
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
values = {'<srcalias>':srcalias, '<dstalias>':dstalias}
data = replace_all(data, values)
temp.write(data)
temp.write("\n")
temp.write(listjobs)
temp.seek(0)
然后,我想在这里的另一部分代码中使用它-
with temp() as f:
count = 1
for line in f:
equal = '='
if (str(count) + equal) in line:
....
如何重新使用已创建的临时文件?
最佳答案
您不必调用它:
with temp as f:
count = 1
for line in f:
或简单地
with temp:
count = 1
for line in temp:
该对象已经是上下文管理器。您必须将它与
open()
混淆,在该函数中对该函数的调用会生成一个新的文件对象,然后将该文件对象用作上下文管理器。请注意,在
with
语句的末尾,将关闭temp
文件对象。