##練習(xí): 復(fù)制文件
def read_file():
try:
f = open('d:\ip1.log','r')
f_copy = open('d:\ip2.log','a')
try:
while True:
s = f.readline()
if not s:
break
f_copy.write(str(s))
finally:
f_copy.close()
f.close()
print("文件已關(guān)閉")
except IOError:
print("文件打開失敗")
read_file()
print("programing end!")
##練習(xí): 復(fù)制文件--與上面等效
# with語句
# 語法: with 表達(dá)式1 [as variables 1], 表達(dá)式2 [as 變量名2], ...
# 作用: 對于資源訪問的場合,確保使用過程中,不管是否發(fā)生異常,都會執(zhí)行必要的清理操作,并釋放資源;
# 如, 文件的打開關(guān)閉、線程中所的自動獲取和釋放,鍵盤鼠標(biāo)等共享設(shè)備
# with 語句和try-finally 相似,無論異常與否都會釋放資源, as子句用于綁定表達(dá)式創(chuàng)建的對象
def copy_file(file_source, file_target):
try:
with open(file_source,'rb') as f, open(file_target,'ab') as f_copy:
while True:
s = f.read(4096)
if not s:
break
f_copy.write(s)
print("文件復(fù)制成功")
except:
print("文件復(fù)制失敗")
def main():
file_source = input('請輸入源文件:')
file_target = input('請輸入目標(biāo)文件:')
copy_file(file_source,file_target)
print("programing end!")
main()
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
