TemporaryFileWrapper实例没有__call__方法

时间:2014-08-26 16:14:01

标签: python with-statement temporary-files contextmanager

我正在生成以下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:   
....

如何重复使用我制作的临时文件?

1 个答案:

答案 0 :(得分:4)

您无需致电:

with temp as f:
    count = 1
    for line in f:

或只是

with temp:
    count = 1
    for line in temp:

该对象已经一个上下文管理器。你必须把它与open()混淆,在那里调用该函数产生一个新的文件对象,然后将其用作上下文管理器。

考虑到with语句末尾将关闭temp文件对象。