但是我得到了(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'
请在这个问题上帮助我。提前谢谢你。
答案 0 :(得分:1)
实际的功能名称为truncate
而不是turncate
! (任何半个体面的Python代码编辑器都会自动完成它)
无论如何,要做出建设性的回答:当你这样做时:
target = open(to_file, 'w')
由于w
模式,您已经截断了文件(将其设置为0大小)。因此,不需要truncate
,turncate
或其他任何内容。这项工作已经完成。