Here's the code
from sys import argv
script,from_file, to_file = argv
open(to_file,'w').write(open(from_file).read())
I'm new to python, and I'm Learning Python the Hard Way, on the extra credit for one problem, it says the writer of the book was able to make the code one line long, so I managed to get it down to 3 lines, but I'm stuck.
Care to help?
Oh, and the code copies the contents of one file to another, or it is meant to. That's my goal.
It is possible to do this as one expression i.e. without needing semicolons:
__import__('shutil').copy(__import__('sys').argv[1], __import__('sys').argv[2])
or
open(__import__('sys').argv[2], "w").write(open(__import__('sys').argv[1]).read())
Of course, nobody in their right mind would prefer this to your sample code. The only change I would make is that there's no reason to assign the file names to temporary variables:
from sys import argv
open(argv[1],'w').write(open(argv[2]).read())
A more Pythonic way of writing this would be:
import sys
with open(sys.argv[1]) as src, open(sys.argv[2]) as dest:
for line in src:
dest.write(line)
and then you could start using argparse
to make the command-line reading more robust...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With