non-uniform string substituion

7stud bbxx789_05ss at yahoo.com
Wed Feb 13 22:37:14 EST 2008


On Feb 13, 4:03 pm, Horacius ReX <horacius.... at gmail.com> wrote:
> Hi,
>
> I have a file with a lot of the following ocurrences:
>
> denmark.handa.1-10
> denmark.handa.1-12344
> denmark.handa.1-4
> denmark.handa.1-56
>
> ...
>
> distributed randomly in a file. I need to convert each of this
> ocurrences to:
>
> denmark.handa.1-10_1
> denmark.handa.1-12344_1
> denmark.handa.1-4_1
> denmark.handa.1-56_1
>

Is each one of those a line in the file?  Or are those words
distributed throughout the file?  If each one is a line, try this:

import os

input = open('data.txt')
output = open('temp.txt', 'w')

for line in input:
    if line.startswith('denmark.handa.'):
        output.write('%s_1\n' % line.strip())
    else:
        output.write(line)

os.remove('data.txt')
os.rename('temp.txt', 'data.txt')



More information about the Python-list mailing list