Skip to content Skip to sidebar Skip to footer

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 da

Solution 1:

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

Solution 2:

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

Post a Comment for "What's Wrong With This Method For Copying A File In Python?"