Python文件復制
# 寫程序實現復制文件的功能
# 要求:
# 1. 源文件路徑和目標文件路徑需要手動輸入
# 2. 要考慮文件關閉的問題
# 3. 要考慮復制超大文件的問題
# 4. 要能復制二進制文件
def copy_file():
'''
此函數實現文件復制功能
source_dir:源文件路徑
target_dir:目標文件路徑
''' source_dir = input("請輸入源文件路徑:") target_dir = input("請輸入目標文件路徑:") try: f = open(source_dir,'rb') try: try: f2 = open(target_dir,'wb') # 可能突然斷電或者U盤被拔出了 try: for i in f: f2.write(i) f.close() f2.close() finally: f2.close() except OSError: print("打開寫文件失敗") return False finally: f.close() except OSError: print("打開讀文件失敗") return False copy_file()
下面的是改良之后的版本,避免過多次數的進行磁盤操作
# 1. 寫程序實現復制文件功能:
# 要求:
# 1. 源文件路徑和目標文件路徑需手動輸入
# 2. 要考慮關閉文件問題
# 3. 要考慮復制超大文件問題
# 4. 要能復制二進制文件
def mycopy(src_file, dst_file):
"""此函數的功以實現復制文件
src_file : 源文件名
dst_file : 目標文件名
"""
try: fr = open(src_file, "rb") # fr讀文件 try: try: fw = open(dst_file, 'wb') # fw寫文件 try: while True: data = fr.read(4096) if not data: break fw.write(data) except: print("可能U盤被拔出...") finally: fw.close() # 關閉寫文件 except OSError: print("打開寫文件失敗") return False finally: fr.close() # 關閉讀文件 except OSError: print("打開讀文件失敗") return False return True s = input("請輸入源文件路徑名: ") d = input("請輸入目標文件路徑名: ") if mycopy(s, d): print("復制文件成功") else: print("復制文件失敗")
下面是with語句改寫后的代碼:
# 1. 寫程序實現復制文件功能:
# 要求:
# 1. 源文件路徑和目標文件路徑需手動輸入
# 2. 要考慮關閉文件問題
# 3. 要考慮復制超大文件問題
# 4. 要能復制二進制文件
def mycopy(src_file, dst_file):
"""此函數的功以實現復制文件
src_file : 源文件名
dst_file : 目標文件名
"""
try: with open(src_file, "rb") as fr,open(dst_file, 'wb') as fw: # fr讀文件 while True: data = fr.read(4096) if not data: break fw.write(data) except OSError: print("打開讀文件失敗") return False except: print("可能U盤被拔出...") return True s = input("請輸入源文件路徑名: ") d = input("請輸入目標文件路徑名: ") if mycopy(s, d): print("復制文件成功") else: print("復制文件失敗")