Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, how could I make this three line code into a one line code?

Tags:

python

copy

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.

like image 209
Andrew McCollam Avatar asked Dec 03 '22 10:12

Andrew McCollam


1 Answers

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...

like image 107
Katriel Avatar answered Feb 16 '23 22:02

Katriel