【问题标题】:"Can't assign to function call" using "with"使用“with”“无法分配给函数调用”
【发布时间】:2015-02-02 17:54:36
【问题描述】:

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

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 open('/Users/jmanley/Desktop/Table.sql', 'wb') as outfile:...

标签: python python-3.x with-statement


【解决方案1】:

请注意:

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

【讨论】:

    猜你喜欢
    • 2015-04-23
    • 1970-01-01
    • 2017-03-01
    • 2015-03-27
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多