Append and Truncating together in Python -
so, @ exercise 16 of zed shaw's python book.
i thought of trying out both append , truncate on same file. know, not make sense. but, new , trying learn happen if used both.
so, first opening file in append mode , truncating , writing it.
but, truncate not working here , whatever write gets appended file.
so, can kindly explain why truncate not work ? though opening file in append mode first, believe calling truncate function after , should have worked !!!
following code:
from sys import argv script, filename = argv print "we're going erase %r." %filename print "if don't want that. hit ctrl-c (^c)." print "if want that, hit return." raw_input("?") print "opening file..." target = open(filename, 'a') print "truncating file. goodbye!" target.truncate() print "now i'm going ask 3 lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "i'm going write these file." target.write(line1 + "\n" + line2 + "\n" + line3) print "and finally, close it." target.close()
truncate file’s size. if optional size argument present, file truncated (at most) size. size defaults current position.
when open file 'a' mode, position @ end of file.
you can this
f = open('myfile', 'a') f.tell() # show position of cursor # can see, position @ end f.seek(0, 0) # put position @ begining f.truncate() # works !! f.close()
Comments
Post a Comment