【发布时间】:2012-07-21 16:55:31
【问题描述】:
我正在阅读 Zed Shaw 的“Learn Python The Hard Way”。我要练习 17 次(http://learnpythonthehardway.org/book/ex17.html),并在额外的积分 2 和 3 上碰壁。Zed 希望我通过消除任何不必要的东西来缩短脚本(他声称他可以让它运行脚本中只有一行)。
这是原始脚本...
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."
output.close()
input.close()
这就是我能够将脚本缩短到并仍然让它正常运行的内容(正确的意思是脚本成功地将预期的文本复制到预期的文件)...
from sys import argv
from os.path import exists
script, from_file, to_file = argv
input = open (from_file)
indata = input.read ()
output = open (to_file, 'w')
output.write (indata)
我摆脱了打印命令和两个关闭命令(如果我错误地使用了“命令”,请原谅......我对编码非常陌生,还没有掌握行话)。
我尝试进一步缩短脚本的任何其他内容都会产生错误。例如,我尝试将“input”和“indata”命令组合成一行……
input = open (from_file, 'r')
然后我将脚本中的所有“indata”引用更改为“input”...
from sys import argv
from os.path import exists
script, from_file, to_file = argv
input = open (from_file, 'r')
output = open (to_file, 'w')
output.write (input)
但我得到以下类型错误...
new-host:python Eddie$ python ex17.py text.txt copied.txt
Traceback (most recent call last):
File "ex17.py", line 10, in <module>
output.write (input)
TypeError: expected a character buffer object
您将如何进一步缩短脚本...或将其缩短为仅一行,就像 Zed 建议的那样?
【问题讨论】:
-
我认为如果您可以不发布您的代码的当前副本并就错误和优化寻求帮助会更有帮助。跨度>
-
练习的重点是减少到一行?由于您正在复制文件,因此只需使用
copy -
谢谢@arxanas...不知道有作业标签。
-
感谢@Levom 的建议...在以后的问题中会记住它。
标签: python