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

2024-09-27 21:29:51 发布

您现在位置: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()

Tags: 文件tofromimportreadinputdataexists
2条回答

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

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

而且,一般来说,最好只使用^{},而不要重新发明这个特殊的轮子。很好地复制文件可能很复杂(我至少用some authority)。你知道吗

相关问题 更多 >

    热门问题