Python:如何使这段代码长一行呢?

时间:2015-02-27 02:48:58

标签: python python-2.7

如何使这段代码长一行?我正在练习“艰难学习Python”#34;并且讲师说他只能在一行中编写这段代码。

 #Argv is imported from the system library
    from sys import argv
    #Exists is imported from the os.path library
    from os.path import exists
    #script, from_file, and to_file are assigned to argv
    #to ask for the user's input upon start of the program
    script, from_file, to_file = argv
    #This will print the following string
    print "Copying from %s to %s" % (from_file, to_file)
    #Open the wanted file is assigned to in_file automatically
    #opens as read only. In_file.read is assigned to indata
    in_file = open(from_file)
    indata = in_file.read()
    #The string will printed and %d will be replaced by the len of indata
    print "The input file is %d bytes long" % len(indata)
    #The string below will be printed and will True/False whether the file exists
    #It will ask the user if he/she wants to continue
    print "Does the output file exist? %r" % exists(to_file)
    print "Ready, hit RETURN to continue, CTRL-C to abort."
    raw_input()
    #It will open the to file as write mode and assign it to out_file
    #The text document file will be re-written by the text from indata
    out_file = open(to_file, "w")
    out_file.write(indata)
    #The string below will be printed
    print "Alright, all done."
    #The program will now close both files because we are done using them
    out_file.close()
    in_file.close()

谢谢!

3 个答案:

答案 0 :(得分:3)

您只需要:

import shutil
import sys

script, from_file, to_file = sys.argv
shutil.copy(from_file, to_file)

进行实际复制。其余的代码只是注释和打印语句。

答案 1 :(得分:1)

indata = open(from_file).read()

可能是duplicate

答案 2 :(得分:1)

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

^是一行。

;是有用的。 (Zed Shaw在“以困难的方式学习Python”的“常见学生问题”部分中提到了这一点)

我所做的就是简化所有操作,以至于您不需要两次提到相同的变量。