In python, how can I make this three-line code a single code?

Here is 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 in a hard way , in addition to one credit problem, it says the book writer was able to make code one line long, so I managed to get it up to 3 lines, but I'm stuck.

Help?

Oh, and the code copies the contents of one file to another, or is it intended. It is my goal.

+4
source share
7 answers

This can be done as a single expression, that is, without the need to use 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, no one in their right mind would prefer this to your sample code. The only change I would make is that there is no reason to assign file names to temporary variables:

 from sys import argv open(argv[1],'w').write(open(argv[2]).read()) 

More pythonic way of writing:

 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 can start using argparse to make command line reading more reliable ...

+9
source

You can use a semicolon to keep the import statement on the same line. And refer to the elements in argv directly, instead of using variables.

 from sys import argv; open(argv[2],'w').write(open(argv[1]).read()) 
+6
source

Two things you need to know:

1) You can include multiple python statements on the same line, splitting them into semicolons

2) You do not need to move command line parameters to separate variables in order to use them.

+3
source

To avoid multiple __import__ @katrielalex, you could do:

(lambda a:open(a[2],"w").write(open(a[1]).read()))(__import__('sys').argv)

It is shorter, but it is ugly.

+1
source

You can get rid of the second line and the argv link directly in the third. To combine the remaining lines, you can use a semicolon. This is kind of a hoax, but I don't see a better solution, since you have to import sys.

 from sys import argv; open(argv[2],'w').write(open(argv[1]).read()) 
0
source

I study it too.

 from_file, to_file = raw_input("copy from: "), raw_input("copy to: ") open(to_file, 'w').write(open(from_file).read()) 
0
source
 import sys open(sys.argv[3], 'w').write(open(sys.argv[2]).read()) 

probably the best you can do.

-2
source

All Articles