[Tutor] Deleting Lines of text
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Sun, 28 Apr 2002 14:50:35 -0700 (PDT)
On Tue, 16 Apr 2002 pythonhack@yahoo.com wrote:
> as far as i know, it's not possible to edit a file in place. you'll
It's not too hard to do in-place replacements of characters in a file:
###
>>> f = open("test.txt", "w")
>>> f.write("hello world!\n")
>>> f.close()
>>> print open("test.txt").read()
hello world!
>>> f = open("test.txt", "r+")
>>> f.seek(1)
>>> f.write("a")
>>> f.seek(0)
>>> print f.read()
hallo world!
###
So in-place modification isn't bad: it's the insertions and deletions that
cause problems. Insertions and deletions involve shifing all the
characters in a file either left or right when we do an insertion or
deletion. Removing or deleting a line in-place is also problematic
because not all lines are the same length --- some lines are longer than
others.
Text editors provide the illusion that it's easy to edit a file in place.
What often happens is that the file is temporarily held in some data
structure like a list (or linked list! *grin*0, and all manipulations are
done on this structure in memory. Lists are much easier to deal with than
files: it's relatively easy to do insertions or other things.
Finally, when the work is done, a "Save" command will write the contents
of the data structure back to disk. That's why word processors make a
distinction between "editing" and "saving", because editing does
manipulation on a copy of the document in memory, rather than directly on
the file.