1

The program should copy the content of in_file_name to the out_file_name. This is what I have but it keeps crashing.

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()
Conor
  • 39
  • 1
  • 9
  • why not use `shutil.copy` for that? – Dekel Dec 06 '16 at 15:19
  • What do you mean, `keeps crashing`? Please update your post with complete information, including exception output. The exception trace usually points right at the exact problem. – CAB Dec 06 '16 at 15:23

3 Answers3

0

You can use shutil for this purpose

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")    
Renjith Thankachan
  • 4,178
  • 1
  • 30
  • 47
0

There's 2 things:

  1. There's better ways to do this (like using shutil.copy and various other functions in the standard library to copy files)

  2. If it's a binary file, open it in "binary" mode.


Anyway, here's how to do it if you're sticking to manually doing it.

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)

Using std library functions: How do I copy a file in python?

Community
  • 1
  • 1
pradyunsg
  • 18,287
  • 11
  • 43
  • 96
  • That said, when asking a questions, please make sure you have 3 parts: A clear description of the task at hand, What you have tried, a clear description of the error with traceback if there. – pradyunsg Dec 06 '16 at 15:26
0

Here is what I did. Using while ch != "": gave me a hanging loop, but it did copy the image. The call to read returns a falsy value at 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)
ncmathsadist
  • 4,684
  • 3
  • 29
  • 45