额外的功劳3,艰苦学习python练习17

时间:2012-01-23 22:00:19

标签: python

  

可能重复:
  Learn Python the Hard Way Exercise 17 Extra Question(S)

在本练习中,我必须在一行中重写代码。我试着写这样的代码行(来自sys import argv,来自os.path导入存在),但它给了我一个语法错误。所以,我很好奇,我怎么能在一条线上写这个练习呢?

以下是本书的代码:

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 个答案:

答案 0 :(得分: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)