[Tutor] replacing something on last line

Paul Tremblay phthenry@earthlink.net
Mon, 8 Jul 2002 17:53:33 -0400


On Mon, Jul 08, 2002 at 03:17:33AM -0400, Andrei Kulakov wrote:

> rfind from another post is more straighforward.. but you could also use
> reverse method of lists: my_list.reverse(). List could be a list of
> lines in files or a list of words in that line (you'd have to use
> split() string method).
> 

Thanks Andrei (and Gregor too).

The problems with these two methods is that you have to read the
whole file in at once. One of my files is 1.8 megs. Is this too
big? (I have 64 megs of ram.)

I devised my own way using a linux utility called tac (which you
probably know about). Tac reverses the lines in a file. I am
working with an rtf file, and the character I want to substitute
almost always occurs by itself on the last line of the file.
However, if it didn't, I could use Gergor's method, once I have
reversed the file:

os.system('tac file1 > file2)
readObj = open(file2,'r')
line = 1
found_flag = 0
while line:
	if not found_flag:
		result = re.search('}'),line
		if result != None:
			##substitute the last occurence as Gregor showed
			found_flag = 1
			print line, # or write it to another file
	else:
		print line, # or write it to another file
		


This seems like a dirty way to substitute, but it works. Is there
a python way of reversing the lines in a file without reading the
whole file in?

Paul

-- 

************************
*Paul Tremblay         *
*phthenry@earthlink.net*
************************