Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   Changing a line in a text file (http://www.programmingforums.org/showthread.php?t=11183)

Dietrich Aug 26th, 2006 12:16 PM

Changing a line in a text file
 
Let's say I have a text file like this:
one
two
three
four
five
...

and I want to change the line containing 'four' to 'vier'. Right now I read it all into a list, process it and write it all back out. Is there a way to do this on the fly with the existing file?

Arevos Aug 26th, 2006 1:25 PM

Yes and no. You can alter individual bytes of a file. So in the example you provide, where "four" is the same length as the string to replace it, "vier", one could just alter those four bytes. If the size of the word differs, however, one would have to rewrite all bytes in the file that come after it.

For example, if I wished to replace "out" with "in":
:

hello out there
:

hello in there
I'd have to move "there" back one character, as the file size has decreased by one. This would involve rewriting the latter half of the file (highlighted in red).

Thus, for most search and replace operations, there's no real disadvantage to reading the entire file into RAM and altering it there (unless you're likely to run out of RAM).

Dietrich Aug 26th, 2006 2:35 PM

Okay, I can see the problem.
Thanks Arevos


All times are GMT -5. The time now is 3:51 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC