[Tutor] replacing a string in files in a directory
Michael Lange
klappnase at freenet.de
Sat Aug 21 01:32:03 CEST 2004
On Fri, 20 Aug 2004 16:44:15 -0400
Manon.Lamothe at ingcanada.com wrote:
> 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 ?
>
Hi Manon,
if you just want to change the first line in your files, you might want to have a look at the fileinput
module, which has very nice methods for this. With fileinput.input(filename, inplace=1) you can iterate over
the lines in the file and change it's contents on the fly;
and with fileinput.isfirstline() you can check if the current line is the first line in the file.
I hope this helps
Michael
More information about the Tutor
mailing list