如何在python中创建非文本二进制文件的精确副本

时间:2016-12-06 15:18:46

标签: python file binaryfiles

程序应将in_file_name的内容复制到out_file_name。这就是我所拥有的,但它一直在崩溃。

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()

3 个答案:

答案 0 :(得分: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")    

答案 1 :(得分:0)

有两件事:

  1. 有更好的方法(比如使用substring(mycol,43,12) 和标准库中的各种其他功能来复制文件)

  2. 如果是二进制文件,请以“二进制”模式打开。

  3. 无论如何,如果您坚持手动操作,请按照以下步骤操作。

    input.groupBy(x => x("id")).filter(y => y._2.size == 1).map(_._2)

    使用std库函数:How do I copy a file in python?

答案 2 :(得分:0)

这就是我所做的。使用while ch != "":给了我一个死循环,但是确实复制了图像。对read的调用在EOF处返回虚假值。

from sys import argv
donor = argv[1]
recipient = argv[2]
# read from donor and write into recipient
# with statement ends, file gets closed
with open(donor, "rb") as fp_in:
    with open(recipient, "wb") as fp_out:
        ch = fp_in.read(1)
        while ch:
            fp_out.write(ch)
            ch = fp_in.read(1)