2016-12-06 64 views
0

程序應該將in_file_name的內容複製到out_file_name。這是我的,但它不斷崩潰。如何在python中創建非文本二進制文件的精確副本

in_file_name = input('Enter an existing file: ') 
out_file_name = input('Enter a new destination file: ') 

try: 
    in_file = open(in_file_name, 'r') 
except: 
    print('Cannot open file' + ' ' + in_file_name) 
    quit() 

size = 0 
result = in_file.read(100) 
while result!= '': 
    size += len(result) 
    result = in_file.read(100) 

print(size) 
in_file.close() 
try: 
    out_file = open(out_file_name, 'a') 
except: 
    print('Cannot open file' + ' ' + out_file_name) 
    quit() 

out_file.close() 
+0

爲什麼不使用該'shutil.copy'? – Dekel

+0

你是什麼意思,「不斷崩潰」?請更新您的帖子,並提供完整的信息,包括異常輸出。異常跟蹤通常指向正確的問題。 – CAB

回答

0

您可以使用shutil用於此目的

from shutil import copyfile 
in_file_name = input('Enter an existing file: ') 
out_file_name = input('Enter a new destination file: ') 
try: 
    copyfile(in_file_name, out_file_name) 
except IOError: 
    print("Seems destination is not writable")  
0

有兩件事情:

  1. 有更好的方法來做到這一點(比如在標準庫使用shutil.copy和各種其他功能複製文件)

  2. 如果是二進制文件,請打開我t在「二進制」模式下。


總之,這裏是如何做到這一點,如果你堅持做手工。

orig_file = "first.dat" 
copy_file = "second.dat" 

with open(orig_file, "rb") as f1: 
    with open(copy_file, "wb") as f2: 
     # Copy byte by byte 
     byte = f1.read(1) 
     while byte != "": 
      f2.write(byte) 
      byte = f1.read(1) 

使用std庫函數:How do I copy a file in python?

+0

也就是說,當提出問題時,請確保您有3個部分:手頭任務的明確描述,您嘗試的內容,如果存在回溯的明確描述。 – pradyunsg

相關問題