我正在尝试编写一个脚本,该脚本将读取目录中的所有文件并将其转储到单个文件中。我所拥有的是:
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
。我只是错过了一些非常明显的东西吗?
答案 0 :(得分:3)
请注意:
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: