[Tutor] replacing something on last line

Andrei Kulakov ak@silmarill.org
Mon, 8 Jul 2002 18:06:39 -0400


On Mon, Jul 08, 2002 at 05:53:33PM -0400, Paul Tremblay wrote:
> 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?
>
Yes but it's kind of complex. You have to f.seek() to seek to almost
end of file, then file.read(block) then you can read the block and see
if that word's in there.

But since you want to replace it, you'd still have to read all the file
in and re-write it to disk; besides, 1.8mb is no big deal, but test how
long it takes..

> 
> Paul
> 
> -- 
> 
> ************************
> *Paul Tremblay         *
> *phthenry@earthlink.net*
> ************************
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org