2017-03-25 39 views
0

我正在學習Python,我是一個超級初學者! 我剛完成一項練習並想創建它的變體。 我的問題是,當使用IF/ELSE聲明時,我該如何避免使用「out_file = open(to_file,'w')out_file.write(indata)」兩次使用 。 在此先感謝!學習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) 

if exists(to_file): 
    print "File already exists, override?" 
    raw_input() 
else: 
    out_file = open(to_file,'w') 
    out_file.write(indata) 

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

print"Done." 

out_file.close() 
in_file.close() 
+0

我想你已經偶然發現了一個主要原因,爲什麼[函數](http://anh.cs.luc.edu/python/hands-on/3.1/ handsonHtml/functions.html#function-parameters)存在:) – jDo

+0

正如我所說的,我剛開始深入編碼世界。所以,請給我一個例子,讓我可以學習! ;) –

回答

1

目前您的腳本並沒有真正考慮用戶的輸入是否覆蓋,而且您不管輸入如何都會覆蓋。它看起來像你要考慮他們的意見,所以我建議是這樣的:

proceed = False 
if exists(to_file): 
    print "File already exists, override?" 
    ans = raw_input("y/n: ") 
    if ans == "y": 
     proceed = True 
else: 
    proceed = True 

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

此外,你可能會想要做一些錯誤處理,如果from_file不存在的,因爲在那種情況下調用到open()將增加IOError - 見https://docs.python.org/2/library/functions.html#open

+0

我喜歡使用'proceed'將兩個嵌套條件轉換成一個標誌來寫入文件。我也喜歡這個答案只打開輸出文件_if_用戶將寫入它。並呼籲需要處理更多的錯誤 - 非常好。 –

+0

非常感謝。我只想在文件已經存在的情況下考慮用戶輸入。 –