0

Hey guys so I'm a beginner at python and I'm going through assigning multiply variables and I come across this problem:

script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}")

#we could do these two on one line, how?
in_file, indata = open(from_file), infile.read 

The code on the last line isn't running and I'm unsure how to format it the right way. Anyone know how?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72

1 Answers1

2

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

Chase
  • 5,315
  • 2
  • 15
  • 41
  • ok thankyou so much! I'm learning from the book "Learn python the hard way" and the "with function hasn't been introduced yet – Pianoman_ 4 Jul 21 '20 at 13:41
  • @Pianoman_4 that's ok, the official docs have all the explanations you could possibly need, I've linked that for `with` – Chase Jul 21 '20 at 13:42
  • ok thankyou! also for note taking what's a good way to organize cause i just list every key term i write down – Pianoman_ 4 Jul 21 '20 at 13:43
  • @Pianoman_4 you mean keywords like `with`, `try/except`, `for`, `if`? or also functions like `open`? You shouldn't have to note them down, whenever you need a refresher on them, you can simply look at the official docs. – Chase Jul 21 '20 at 13:45
  • I'm saying for more general note-taking, syntax isn't too hard to understand just the concepts – Pianoman_ 4 Jul 21 '20 at 13:46
  • @Pianoman_4 [This question](https://cseducators.stackexchange.com/questions/2687/note-taking-for-self-studying) may help. I cannot elaborate on any unrelated topics on comments unfortunately. – Chase Jul 21 '20 at 13:47