Python:如何使这段代码只有一行?

Python:如何使这段代码只有一行?,python,python-2.7,Python,Python 2.7,我怎样才能使这个代码只有一行?我正在做一个关于“艰苦学习Python”的练习,老师说他只能用一行代码来编写这段代码 #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 assi

我怎样才能使这个代码只有一行?我正在做一个关于“艰苦学习Python”的练习,老师说他只能用一行代码来编写这段代码

 #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()
谢谢大家!

indata = open(from_file).read()
大概

可能你所需要的只是:

import shutil
import sys

script, from_file, to_file = sys.argv
shutil.copy(from_file, to_file)
进行实际复制。代码的其余部分只是注释和打印语句。

您只需要:

import shutil
import sys

script, from_file, to_file = sys.argv
shutil.copy(from_file, to_file)
from sys import argv; script, from_file, to_file = argv; out_file = open(to_file, 'w').write(open(from_file).read())
进行实际复制。代码的其余部分只是注释和打印语句

from sys import argv; script, from_file, to_file = argv; out_file = open(to_file, 'w').write(open(from_file).read())
^那是一行

);这是有用的。(Zed Shaw在“艰苦学习Python”的“普通学生问题”部分提到了这一点)

我所做的是将所有的事情简化到不需要重复提到的同一个变量的程度

^那是一行

);这是有用的。(Zed Shaw在“艰苦学习Python”的“普通学生问题”部分提到了这一点)


我所做的是将所有事情简化到不需要重复提到的同一变量。

你能发布练习解释吗?可能重复的你能发布练习解释吗?可能重复的我还有另一个问题,因为在90分钟过去之前,它不会让我有多个问题。我是Python新手,为什么我的程序要打印h的值60次而不是我希望它做的(h*60)?谢谢!:)def练习(小时):打印“您已经练习了%s小时”%hours minutes=60*h打印“您已经练习了%s分钟”%minutes h=raw_输入(“您花了多少小时练习?”)练习(h)因为
h
是一个字符串而不是一个数字。我还有一个问题,因为在90分钟过去之前,它不允许我回答多个问题。我是Python新手,为什么我的程序要打印h的值60次而不是我希望它做的(h*60)?谢谢!:)def练习(小时):打印“您已经练习了%s小时”%hours minutes=60*h打印“您已经练习了%s分钟”%minutes h=raw_输入(“您花了多少小时练习?”)练习(h),因为
h
是字符串而不是数字。