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 thest two on one line, how?
in_file = open(from_file)
indata = in_file.read()
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()
練習(xí)
from sys import argv
script, from_file, to_file = argv
# 這個(gè)程序不能用close(),因?yàn)闆]有變量去引用文件對象,解釋器會去偵測到打開的文件窄做,自動關(guān)閉它核无。
# 當(dāng)執(zhí)行完這一行的時(shí)候瀑晒,文件自動就被關(guān)閉了隅熙。
open(to_file,'w').write(open(from_file,'r').read())
4.不關(guān)閉文件,它會直到程序結(jié)束為止一直占用系統(tǒng)資源
點(diǎn)我有驚喜
exercise15~17小結(jié):
建立文件
打開文件
讀取文件
寫入文件
關(guān)閉文件
點(diǎn)擊