【问题标题】:TemporaryFileWrapper instance has no __call__ methodTemporaryFileWrapper 实例没有 __call__ 方法
【发布时间】:2023-04-03 16:40:02
【问题描述】:

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

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

【问题讨论】:

    标签: python with-statement temporary-files contextmanager


    【解决方案1】:

    你不必调用它:

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

    或者干脆

    with temp:
        count = 1
        for line in temp:
    

    对象已经是一个上下文管理器。您一定把这与open() 混淆了,它是对该函数的调用产生一个新的文件对象,然后将其用作上下文管理器。

    考虑到with 语句结束时temp 文件对象将被关闭。

    【讨论】:

    • 谢谢!有没有办法让它打开?我实际上是在创建它,使用它,将它用于外部应用程序,然后再使用它。
    • 那么不要在with 语句中使用它。删除with 行,取消缩进块。
    • 这就是with 语句的全部作用。启动时调用temp.__enter__(),完成时调用temp.__exit__(),如果有异常,可选择传入异常。 temp.__exit__() 关闭文件。这个想法是当块退出时,无论块中发生什么,您都会自动关闭文件。
    • 如果你不想关闭它,那么你根本就不要使用with。
    • 非常感谢Martjin!确认工作。还有另一个问题,但与 3rd 方应用程序有关,所以我要先解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 2012-07-04
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多