##練習: 復制文件
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("文件已關閉")
except IOError:
print("文件打開失敗")
read_file()
print("programing end!")
##練習: 復制文件--與上面等效
# with語句
# 語法: with 表達式1 [as variables 1], 表達式2 [as 變量名2], ...
# 作用: 對于資源訪問的場合,確保使用過程中,不管是否發生異常,都會執行必要的清理操作,并釋放資源;
# 如, 文件的打開關閉、線程中所的自動獲取和釋放,鍵盤鼠標等共享設備
# with 語句和try-finally 相似,無論異常與否都會釋放資源, as子句用于綁定表達式創建的對象
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("文件復制成功")
except:
print("文件復制失敗")
def main():
file_source = input('請輸入源文件:')
file_target = input('請輸入目標文件:')
copy_file(file_source,file_target)
print("programing end!")
main()
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

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