Search and replace a specific word in a file object.

Discussion in 'Python' started by sebb, Jan 11, 2004.

  1. sebb

    sebb Guest

    I want to know how to search for a word in a file object and then
    replace that word with another string. I would like to know the
    easiest way to do it.

    Thanks.
    sebb, Jan 11, 2004
    #1
    1. Advertising

  2. Hi !


    You can try this :

    def remplacerdansfichiertxt(file, listeremplacement, filout):
    # remplacement dans un fichier texte (et non binary)
    import os,os.path,re
    if os.path.isdir(file):
    print(file+' is a Directory !')
    else:
    data = open(file, "rb").read()
    if '\0' in data:
    print('it's a binary file')
    else:
    newdata=data
    for chaine,remplacement in listeremplacement :
    newdata = re.sub(chaine, remplacement, newdata)
    if newdata != data:
    f = open(filout, "wb")
    f.write(newdata)
    f.close()
    print(file,';',chaine,' => ',remplacement,':',filout,' :
    OK')

    in the call, the parameter "listeremplacement" is like
    [('oldVal','newVal'),('aaa','bbbb'),('qwerty','azerty')]

    @-salutations
    --
    Michel Claveau
    Michel Claveau/Hamster, Jan 11, 2004
    #2
    1. Advertising

  3. sebb

    Miki Tebeka Guest

    Hello,

    Use the fileinput module:
    from fileinput import input

    def replace(filename, old, new):
    for line in input(filename, inplace=1):
    print line.replace(old, new)

    HTH.
    Miki
    Miki Tebeka, Jan 12, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. TB
    Replies:
    2
    Views:
    6,327
  2. Ola K
    Replies:
    2
    Views:
    520
    Ola K
    Dec 10, 2006
  3. Mark Toth
    Replies:
    3
    Views:
    128
    Mark Toth
    Dec 30, 2007
  4. qanda
    Replies:
    8
    Views:
    109
    John Bokma
    Sep 5, 2003
  5. William FERRERES
    Replies:
    7
    Views:
    204
    William FERRERES
    Jul 9, 2007
Loading...

Share This Page