1. 程式人生 > >《Learn python3 the hard way》ex17

《Learn python3 the hard way》ex17

今天新學了一個os.path 這個包裡exists這個功能,驗證是否存在,存在則顯示TRUE不存在則顯示False。

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print(f"Copying from {from_file} TO {to_file}")

#we could do these two on one line, how?
in_file = open(from_file)  # 開啟文件
indata = in_file.read()  # 把文件內容賦值給indata變數
print(f"The input file is {len(indata)} bytes long") #顯示文件位元組 print(f"Does the output file exist?{exists(to_file)}") #另一個文件是否存在 print("Ready,hit RETURN to continue, CTRL-C to abort.") #詢問是否要繼續 input() out_file = open(to_file, 'w') # 以只寫的方式開啟另一個文件 out_file.write(indata) # 將第一個文件內容寫入第二個文件 print
("Alright, all done.") # 提示已經完成 #把兩個文件關閉 out_file.close() in_file.close()