简体   繁体   中英

How can I shorten this Python script for copying a file into another file?

Python newbie here. Just starting to learn. I am following "How to Learn Python the Hard Way" and one of the exercises is to shorten a script as much as we can. I have hit a sort of road block and I'd appreciate any insight. The code simply takes a file and copies it into another file. This is what the code looked like at first.

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)

in_file = open(from_file)
indata = in_file.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()

out_file = open(to_file, 'w')
out_file.write(indata)

print "Alright, all done."

out_file.close()
in_file.close()

Now the code looks like this:

 from sys import argv; script, from_file, to_file = argv; 

 in_data = open(from_file).read()

 out_file = open(to_file, 'w').write(in_data)

Is it cheating to use a semicolon as a way to keep two lines as one line? I got rid of some of the features because I felt like they were pointless for this particular exercise. The author said he was able to get the script down to one line and I would appreciate any suggestions for how to do this. The script works this way and I've tried fitting it all onto one or two lines with semicolons but I was wondering if there's a better solution. Thanks very much.

You can use shutil.copyfile or shutil.copyfileobj .

http://docs.python.org/2/library/shutil.html

BTW:

The purpose of shortening your code is usually to make it easier to understand. While using semicolons to merge several statements in one line doesn't count as cheating, it makes your code less readable.

Well, one-liner, I suppose:

open('outfile','w').write(open('infile').read())

This makes me cringe to write code like this. In fact, don't ever have bare open file handles, use open as a context manager:

with open('infile') as r, open('outfile','w') as w:
    #do things to r and w here

It's both compact and good coding practice.

re: semicolons. Beautiful is better than ugly. Avoid them at all cost, unless you're contributing to some code golf .

from sys import argv;
script, from_file, to_file = argv;
open(to_file, 'w').write(open(from_file).read())

I am also learning this book as a code beginner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM