简体   繁体   English

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

[英]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 . 这类似于“ 学习Python困难的方式”中的 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()

You must open the files in binary mode ( "rb" and "wb" ) when copying. 复制时,必须以二进制模式( "rb""wb" )打开文件。

Also, it's in general better to just use shutil.copyfile() and not re-invent this particular wheel. 而且,通常最好只使用shutil.copyfile()而不是重新发明这个特定的轮子。 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. 在读取结果之前,请尝试使用seek将文件指针倒回到开头。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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