0

Python新手在这里。刚开始学习。我正在关注“如何艰难地学习 Python”,其中一个练习是尽可能地缩短脚本。我遇到了某种障碍,我将不胜感激。该代码只是获取一个文件并将其复制到另一个文件中。这就是代码最初的样子。

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)

in_file = open(from_file)
indata = in_file.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()

out_file = open(to_file, 'w')
out_file.write(indata)

print "Alright, all done."

out_file.close()
in_file.close()

现在代码如下所示:

 from sys import argv; script, from_file, to_file = argv; 

 in_data = open(from_file).read()

 out_file = open(to_file, 'w').write(in_data)

使用分号将两行保持为一行是作弊吗?我去掉了一些功能,因为我觉得它们对于这个特定的练习毫无意义。作者说他能够将脚本简化为一行,我将不胜感激有关如何执行此操作的任何建议。该脚本以这种方式工作,我尝试将其全部安装到一两行带分号的行中,但我想知道是否有更好的解决方案。非常感谢。

4

3 回答 3

2

您可以使用shutil.copyfileshutil.copyfileobj

http://docs.python.org/2/library/shutil.html

顺便提一句:

缩短代码的目的通常是为了更容易理解。虽然使用分号在一行中合并多个语句不算作弊,但它会降低您的代码的可读性。

于 2013-11-03T05:33:22.370 回答
2

好吧,我想,单线:

open('outfile','w').write(open('infile').read())

这让我畏缩写这样的代码。事实上,永远不要有裸open文件句柄,open用作上下文管理器:

with open('infile') as r, open('outfile','w') as w:
    #do things to r and w here

它既紧凑又很好的编码实践。

回复:分号。美丽总比丑陋好。不惜一切代价避免它们,除非您正在为一些代码高尔夫做出贡献。

于 2013-11-03T05:40:37.380 回答
0
from sys import argv;
script, from_file, to_file = argv;
open(to_file, 'w').write(open(from_file).read())

作为代码初学者,我也在学习这本书。

于 2016-01-14T07:26:40.283 回答