簡體   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