繁体   English   中英

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

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

我不明白为什么我的新文件中包含许多原始文件中没有的特殊字符。 这类似于“ 学习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()

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

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

在读取结果之前,请尝试使用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