Search and replace a specific word in a file object.

S

sebb

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.
 
M

Michel Claveau/Hamster

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
 
M

Miki Tebeka

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top