lpthw练习17课代码:
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)
# we could do these two on one line, how?
in_file = open(from_file)
indata = in_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()
out_file = open(to_file, 'w')
out_file.write(indata)
print "Alright, all done."
在研究练习中,它会要求您使用两行命令
in_file = open(from_file)
indata = in_file.read()
并使其成为一行命令。
我这样做了
indata = open(from_file).read()
工作得很好。
但后来我尝试将第二组命令放在一起
out_file = open(to_file, 'w')
out_file.write(indata)
到
out_file = open(to_file, 'w').write(indata)
并且它没有像我想象的那样工作。许多人已经发布了使这些命令成为一行的正确方法,但我想知道为什么我的第一种方法不起作用。这里的任何人都可以给我一个简短的解释吗?