这种在Python中复制文件的方法有什么问题?

DEd*_*s57 0 python

我不明白为什么我的新文件中有一堆特殊字符不在原始文件中.这与Learn Python The Hard Way中的 ex17类似.

#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()
Run Code Online (Sandbox Code Playgroud)

unw*_*ind 5

复制时必须以二进制模式("rb""wb")打开文件.

而且,通常更好的是只使用shutil.copyfile()而不是重新发明这个特定的轮子.很好地复制文件可能很复杂(我说至少有一些权限).