[Tutor] replacing a string in files in a directory

Manon.Lamothe at ingcanada.com Manon.Lamothe at ingcanada.com
Fri Aug 20 22:44:15 CEST 2004


This is my code

bbvardir = '/home/bb/bb19c/ext/manon'
bbvarfiles = os.listdir(bbvardir)

for item in bbvarfiles:
     dirfile = os.path.join(bbvardir, item)
     print '_______________________________________'
     bbfile = open(dirfile, 'r+')
     lines = bbfile.readlines()
     if len(lines) >= 1:
         firstline = lines[0].strip()
         print 'firstline ' + firstline
         colour = firstline.split()[0]
         print 'colour ' + colour
         if colour == 'red':
              withchange = string.replace(firstline,'red','green_green')
              # withchnage = withchange + '\n'
              print 'withchange: ' + withchange
              bbfile.seek(0)
              bbfile.writelines(withchange)

         bbfile.close()

my replacement string is longer than the original one, and when I write the
replacement in the file, the second line is overwritten.

This is the original file:
red bonjour tous le monde 1
ceci est ma 2ieme ligne ici
red

and the final file:
green_green bonjour tous le monde 1
t ma 2ieme ligne ici
red

How can I fix that code ?

_________________
Manon Lamothe

----------------
This email transmission may contain personal information. By collecting,
using or disclosing any of the information contained herein, you hereby
agree to abide by our Company's Privacy Promise and all applicable privacy
laws. Our Privacy Promise is available at: www.ingcanada.com. If you are
not the intended recipient, or if you have any questions, please contact
the sender.
------------------
Ce courriel pourrait contenir des renseignements personnels. En
recueillant, en utilisant ou en communiquant tout renseignement qui y
figure, vous vous engagez à vous conformer à la Promesse en matière de
protection de la vie privée publiée par notre entreprise ainsi qu'à toute
loi canadienne applicable. Notre promesse en matière de protection de la
vie privée est publiée à www.ingcanada.com. Si vous n'êtes pas le
destinataire indiqué ou si vous avez des questions, veuillez communiquer
avec l'expéditeur.




More information about the Tutor mailing list