繁体   English   中英

如何缩短用于将文件复制到另一个文件的Python脚本?

[英]How can I shorten this Python script for copying a file into another file?

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)

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

您可以使用shutil.copyfileshutil.copyfileobj

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

BTW:

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

好吧,我想:

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

它既紧凑又良好的编码习惯。

回复:分号。 美丽胜于丑陋。 不惜一切代价避免使用它们,除非您为某些代码高尔夫做贡献。

from sys import argv;
script, from_file, to_file = argv;
open(to_file, 'w').write(open(from_file).read())

我还以代码初学者的身份学习这本书。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM