简体   繁体   中英

What's wrong with this method for copying a file in Python?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM