《认真学Python》第17题额外问题
我正在学习Zed Shaw的精彩课程《艰难的Python学习》,但是有个额外的问题让我困惑:第9到10行可以合并成一行,这怎么做呢?我试过一些不同的方法,但都没成功。我可以继续往下学,但那样有什么意思呢?
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 too, how?
input = open(from_file)
indata = input.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."
Zed还提到他可以把整个脚本写成一行。我不太明白他这句话的意思。
欢迎你随意帮助我:可以直接给我答案,或者给我一些提示——也许还可以包含一个折叠或隐藏的答案。
16 个回答
6
好吧,你可以直接用“代数替换”来解决,对吧?...前提是你不在乎“用户界面”...
open(to_file, 'w').write(open(from_file).read())
8
shutil 是在Python中进行简单文件复制的工具:
shutil.copy(sys.argv[1], sys.argv[2])
不过,把 import shutil, sys
和这一行放在同一行(中间用分号隔开)看起来会有点奇怪;-)。
21
indata = open(from_file).read()
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。