Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learn Python the Hard Way Exercise 17 Extra Question(S)

Tags:

I'm doing Zed Shaw's fantastic Learn Python The Hard Way, but an extra question has me stumped: Line 9--10 could be written in one line, how? I've tried some different thoughts, but to no avail. I could move on, but what would the fun in that be?

from sys import argv from os.path import exists  script, from_file, to_file = argv  print "Copying from %s to %s" % (from_file, to_file)  # we could do these two on one line too, how? input = open(from_file) indata = input.read()  print "The input file is %d bytes long" % len(indata)  print "Does the output file exist? %r" % exists(to_file) print "Ready, hit RETURN to continue, CTRL-C to abort." raw_input()  output = open(to_file, 'w') output.write(indata)  print "Alright, all done." 

Zed also writes that he could do the whole script in one line. I'm not exactly sure what he means by that.

Feel free to help me however you want: by giving the answer or merely hinting---and perhaps including a collapsed or hidden answer to the question.

like image 314
Kiwi Avatar asked Aug 24 '10 21:08

Kiwi


2 Answers

indata = open(from_file).read() 
like image 198
GSto Avatar answered Oct 16 '22 09:10

GSto


shutil is the way to do one-liner file copies in Python:

shutil.copy(sys.argv[1], sys.argv[2]) 

Putting the import shutil, sys on the same line as this one (with a semicolon in-between, of course) would however be stylistically goofy;-).

like image 23
Alex Martelli Avatar answered Oct 16 '22 09:10

Alex Martelli