0

I don't understand why my new file has a bunch of special characters in it that were not in the original file. This is similar to ex17 in Learn Python The Hard Way.

#How to copy data from one file into another

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

from_data = open(from_file, "r").read()

print "The input file is %d bytes long" % len(from_data)

print "Checking if output file exist..... %r" % exists(to_file)
print "Hit return to continue or Cntl C to quit"

#keyboard input
raw_input()

out_file = open(to_file, "r+")
out_file.write(from_data)

print "Okay all done, your new file now contains:"
print out_file.read()

out_file.close()
alexwlchan
  • 5,699
  • 7
  • 38
  • 49
DEdesigns57
  • 361
  • 1
  • 5
  • 13

2 Answers2

5

You must open the files in binary mode ("rb" and "wb") when copying.

Also, it's in general better to just use shutil.copyfile() and not re-invent this particular wheel. Copying files well can be complex (I speak with at least some authority).

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Well the author forgot to mention that part lol. Let me try that real quick. – DEdesigns57 Feb 13 '15 at 15:55
  • well using rb or wb doesnt seem to work for me. What happens is when I go to print out the new file i hear a beep from my computer then on the console window i see big blank area with special characters on the last line. Then in my text editor i see that that new file contains the data but has nullnullnullnullnullnullnullnull.... at the end of the last line. Whats going on? – DEdesigns57 Feb 13 '15 at 16:17
0

Try rewinding the file pointer back to the beginning using seek before you read the results.

out_file = open(to_file, "r+")
out_file.write(from_data)

print "Okay all done, your new file now contains:"
out_file.seek(0)
print out_file.read()
Kevin
  • 74,910
  • 12
  • 133
  • 166