我通过删除目标文件的内容将源文件的内容复制到目标文件

时间:2017-04-13 19:02:46

标签: python

但是我得到了(AttributeError:'文件'对象没有属性' turncate')

这是我的代码

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "This script erases the cotent of target file and replaces it with the content of source file."
print "Press RETURN to continue or CTRL+C to abort."

print "copying from %s to %s" % (from_file, to_file)

source = open(from_file)
source_read = source.read()

print "Does the output file exists? %r" % exists(to_file)
print "Erasing the content of %s..." % (to_file)

target = open(to_file, 'w')
target.turncate()

print "Writing content of source file to target file.Please wait..."

target.write(source_read)

print "It's done, script credits Deepak H S"

target.close()
source.close()

错误我

:~/pystuff$ python ex15.py new.txt test.txt
This script erases the cotent of target file and replaces it with the content of source file.
Press RETURN to continue or CTRL+C to abort.
copying from new.txt to test.txt
Does the output file exists? True
Erasing the content of test.txt...
Traceback (most recent call last):
  File "ex15.py", line 18, in <module>
    target.turncate()
AttributeError: 'file' object has no attribute 'turncate'

请在这个问题上帮助我。提前谢谢你。

1 个答案:

答案 0 :(得分:1)

实际的功能名称为truncate而不是turncate! (任何半个体面的Python代码编辑器都会自动完成它)

无论如何,要做出建设性的回答:当你这样做时:

target = open(to_file, 'w')

由于w模式,您已经截断了文件(将其设置为0大小)。因此,不需要truncateturncate或其他任何内容。这项工作已经完成。