When a newbie (e.g. me) asks to read / process a text file in python, he often gets answers like:
with open("input.txt", 'r') as f: for line in f:
Now I would like to truncate everything in the file that I read after the special line. After changing the above example, I use:
with open("input.txt", 'r+') as file: for line in file: print line.rstrip("\n\r") #for debug if line.rstrip("\n\r")=="CC": print "truncating!" #for debug file.truncate(); break;
and expect him to throw everything after the first "CC". Running this code on input.txt:
AA CC DD
the console displays (as expected) the following:
AA CC truncating!
but the file "input.txt" remains unchanged!?!?
How can it be? What am I doing wrong?
Edit: After the operation, I want the file to contain:
AA CC
source share