额外学分3,艰苦学习python练习17
可能重复:额外学分3,艰苦学习python练习17,python,Python,可能重复: 在这个练习中,我必须在一行中重写代码。我试图这样编写代码行(从sysimport argv,从os.path import exists),但它给了我一个语法错误。所以,我很好奇,我怎么能把这个练习写在一行上呢 以下是本书中的代码: from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (from_file
在这个练习中,我必须在一行中重写代码。我试图这样编写代码行(从sysimport argv,从os.path import exists),但它给了我一个语法错误。所以,我很好奇,我怎么能把这个练习写在一行上呢 以下是本书中的代码:
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)
indata = open(from_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()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
使用
来分隔语句,而不是,
我认为这个练习的目的不是简单地将行连接起来并用分号分隔。您应该尝试实际最小化代码 例如:
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
可替换为:
with open(to_file, 'w') as output: output.write(indata)
可能的副本。有关单线解决方案,请参见。