艰苦学习Python练习17额外问题(S)

Kiw*_*iwi 21 python python-2.x

我正在做Zed Shaw的奇妙学习Python The Hard Way,但是另外一个问题让我感到难过:第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."
Run Code Online (Sandbox Code Playgroud)

Zed还写道,他可以在一行中完成整个剧本.我不确定他的意思是什么.

随意帮助我,无论你想要什么:通过给出答案或仅仅提示 - 并且可能包括对问题的折叠或隐藏答案.

GSt*_*Sto 20

indata = open(from_file).read()
Run Code Online (Sandbox Code Playgroud)

  • 是的 - 虽然这(以及两行解决方案)将使文件打开时间超过需要,所以你应该在实际代码中避免这种情况(在一行中更好的方法是`将open(from_file)作为f :indata = f.read()`,如果你想保存线条只是为了它的地狱) (13认同)
  • @delnan:我认为这里的意图不是为"它的地狱"保存线条,而是让人们习惯于能够像这样将函数/方法调用链接起来.@Kiwi:在表达式上调用返回对象的方法也是Java中非常常见的模式.例如,考虑一种(现已弃用的)Java方式来打印当前日期:"new Date().toGMTString()". (2认同)

Ale*_*lli 8

shutil是在Python中执行单行文件副本的方法:

shutil.copy(sys.argv[1], sys.argv[2])
Run Code Online (Sandbox Code Playgroud)

import shutil, sys然而,将它放在与此相同的行(当然,在它们之间用分号)将是风格上的傻瓜;-).


das*_*ang 6

那么你可以做"代数替换",对吧?...假设你不关心"UI"......

open(to_file, 'w').write(open(from_file).read())
Run Code Online (Sandbox Code Playgroud)