"Can't assign to function call" 使用 "with"

"Can't assign to function call" using "with"

我正在尝试编写一个脚本来读取目录中的所有文件并将它们转储到一个文件中。我拥有的是:

from glob import glob

directory = glob('/Users/jmanley/Desktop/Table/*')

with outfile as open('/Users/jmanley/Desktop/Table.sql', 'wb'):
    for file in directory:
        with readfile as open(file, 'rb'):
                        outfile.write(readfile.read())

我收到 "can't assign to function call" 作为错误信息,IDLE 将 with 关键字标记为错误位置。

如果我重写脚本以使用 open()close() 方法而不是使用 with 关键字,它可以正常运行:

from glob import glob

directory = glob('/Users/jmanley/Desktop/Table/*')
outfile = open('/Users/jmanley/Desktop/Table.sql', 'wb')

for file in directory:
    readfile = open(file, 'rb')
    outfile.write(readfile.read())
    readfile.close()

outfile.close()

为什么我会收到 "can't assign to function call" 错误?我见过这种情况发生的唯一一次是如果分配被逆转:a + b = variable。我只是错过了一些非常明显的东西吗?

注意:

with foo as bar:

(非常非常粗略地)相当于:

bar = foo

(这与 Python 中 as 的其他用法一致,例如 except ValueError as err:。)

因此当您尝试时:

with outfile as open('/Users/jmanley/Desktop/Table.sql', 'wb'):

您实际上是在尝试分配:

open('/Users/jmanley/Desktop/Table.sql', 'wb') = outfile

显然不正确。相反,您需要反转语句:

with open('/Users/jmanley/Desktop/Table.sql', 'wb') as outfile:

另见 the relevant PEP