我正在阅读 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 建议的那样?