You can't. The reason is that at the time of assigning, infile
is not defined. It's only defined after the fact. And please do not try to, it's incredibly bad coding style and only makes your code harder to read. Remember, python focuses heavily on readability.
I'd like to elaborate more actually, this answer does the same, and I'll be quoting them.
In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variable
Which essentially means both open(from_file)
and in_file.read
(actually in_file.read()
) must be evaluated first. But that's impossible because in_file
does not exist.
Instead try-
with open(from_file) as infile:
indata = infile.read()
# Use indata here
The benefit of with open
is that the file you open
is also automatically closed as soon as with
ends, which is simply great.
P.S- You forgot to call .read
, you call functions with ()
Edit: with
docs are right here