python習題17
阿新 • • 發佈:2018-12-01
1 from sys import argv 2 from os.path import exists 3 4 script, from_file, to_file = argv 5 6 print(f"Copying from {from_file} to {to_file}") 7 8 # We could do these two on line ,how? 9 in_file = open(from_file) 10 indata = in_file.read() 11 12 print(f"The input file is {len(indata)} bytes long") 13 14 print(f"Does the output file exist? {exists(to_file)}") 15 print("Ready, hit RETURN to continue, CTRL-C to abort.") 16 input('>>>>') 17 18 out_file = open(to_file,'w') 19 out_file.write(indata) 20 21 print("Alright, all done.") 22 23 out_file.close() 24 in_file.close()
這個指令碼沒必要在複製之前問你,也沒必要在螢幕上輸出那麼多東西,試著刪掉一些特性,讓他看起來更友好。
from sys import argv from os.path import exists script, from_file, to_file = argv in_file = open(from_file) indata = in_file.read() out_file = open(to_file,'w') to_file.write(indata) print("Alright, all done.")
一行實現
1 from sys import argv 2 3 script, from_file, to_file = argv 4 5open(to_file,'w').write(open(from_file).read())
*為什麼要在程式碼中寫out_file.close():關閉檔案