学习Python困难之路练习17个额外问题

2024-06-01 12:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做Zed Shaw的很棒的Learn 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."

泽德还写道,他可以一行完成整个剧本。我不太清楚他那是什么意思。

你想怎么帮我就怎么帮吧:给我答案,或者只是暗示——也许还包括对这个问题的一个折叠或隐藏的答案。


Tags: theto答案fromimportinputoutputexists
3条回答

shutil是在Python中复制一个线性文件的方法:

shutil.copy(sys.argv[1], sys.argv[2])

然而,将import shutil, sys放在与此行相同的行上(当然,中间有一个分号)在文体上是愚蠢的;-。

indata = open(from_file).read()

你可以做“代数代换”,对吧。。。假设你不在乎“用户界面”。。。

open(to_file, 'w').write(open(from_file).read())

相关问题 更多 >