Hey Kiwi (and whomever else finds this!),
I'm on the same exercise and I believe I've cracked it.
There are two possible readings of Shaw's "I could make this one line long" tease.
- He could make the Python script one line long, upon importing all the necessary commands from the modules, e.g
from sys import argv, etc.
- He could copy the contents of one file to another in one line using the command line.
I personally think he means the latter, but I will explain both solutions for the sake of learning!
The first (Long) solution:
You must acknowledge that you require the importx from y lines in the Python file, otherwise argv and exist won't work because they will only have been implicitly referenced, i.e. you haven't made it clear to Python that you want to use these functions.
The next thing to do is delete all irrelevant code, with irrelevant being code that is written for the benefit of the user, i.e. print, raw_input(), len(), etc.
If you do this, you will be left with:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
indata = open(from_file).read()
out_file = open(to_file, 'w')
out_file.write(indata)
out_file.close()
in_file.close()
To make this even shorter, you can begin nesting the variables and function in one another. This is the same principle as in maths when you could define a function and then substitute the variable representing that function into another function.
For example:
y = x + 3
z = y, which is essentially z = (x + 3)
If you work this through, you can simplify the code down to:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
(open(to_file, 'w').write(open(from_file).read()))
You can then use lots of ; to link up all the lines of code and vio-la you're done.
Note: You don't need to close the files, as you did in the original, as Python will automatically close them upon executing the script.
The second (Short) solution:
If you look at his 'What You Should See' section, he uses cat in the terminal. This is short for concatenation, which is a means of connecting strings together. If you combine it with > you can overwrite the contents of one file with another in one line:
cat from_file.txt > to_file.txt
That's it. One line that will take the contents of one file and put it into another.
Of course, both solutions aren't perfect, as the first isn't truly one line and the second doesn't even use Python!
Feedback appreciated, I only started doing this two days ago...