Joseph
Joseph

Reputation: 177

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

I am trying to write a script that will read all the files in a directory and dump them into a single file. What I have is:

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())

I get "can't assign to function call" as the error message, and IDLE marks the with keyword as the location of the error.

If I rewrite the script to use open() and close() methods rather than using the with keyword, it runs without issue:

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()

Why am I getting the "can't assign to function call" error? The only time I've seen this happen is if an assignment is reversed: a + b = variable. Am I just missing something incredibly obvious?

Upvotes: 0

Views: 1554

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122092

Note that:

with foo as bar:

is (very, very roughly) equivalent to:

bar = foo

(This is consistent with other uses of as in Python, e.g. except ValueError as err:.)

Therefore when you try:

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

you are actually trying to assign:

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

which is clearly incorrect. Instead, you need to reverse the statement:

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

See also the relevant PEP.

Upvotes: 3

Related Questions