额外学分3,艰难学Python 练习17
可能重复的问题:
《艰难的Python学习》第17章额外问题
在这个练习中,我需要把代码改写成一行。我试着把代码写成这样(from sys import argv, from 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()
1 个回答
4
用 ;
来分隔语句,而不是用 ,
。
我觉得这个练习的目的不仅仅是把这些行连接起来,然后用分号隔开。你应该尝试真正地减少代码的量。
比如说:
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
可以替换成:
with open(to_file, 'w') as output: output.write(indata)