Newbie Text Processing Question

James Stroud jstroud at mbi.ucla.edu
Tue Oct 4 23:23:23 EDT 2005


You can edit a file in place, but it is not applicable to what you are doing. 
As soon as you insert the first "<biblio>", you've shifted everything 
downstream by those 8 bytes. Since they map to a physically located blocks on 
a physical drive, you will have to rewrite those blocks. If it is a big file 
you can do something conceptually similar to piping, where the original file 
is read in line by line and a new file is created:

afile = open("somefile.xml")
newfile = open("somenewfile.xml", "w")
for aline in afile:
  if tests_positive(aline):
    newfile.write(make_the_prelude(aline))
    newfile.write(aline)
    newfile.write(make_the_afterlude(aline))
  else:
    newfile.write(aline)
afile.close()
newfile.close()

James

On Tuesday 04 October 2005 20:13, Gregory Piñero wrote:
> That's how Python works. You read in the whole file, edit it, and write it
> back out. As far as I know there's no way to edit a file "in place" which
> I'm assuming is what you're asking?

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list