0

suppose I have a file.txt with line
aaaa = /bbb/ccc/ddd/eee/fff

I would like replace ccc with xxx

I have tried next without success

import re
import fileinput

for line in fileinput.input(file.txt, inplace=True):
    re.sub(r'(ccc)', 'xxx', line)
FelixK
  • 35
  • 4

2 Answers2

0

Try this:


m = re.sub(r'ccc', r'xxx', "/bbb/ccc/ddd/eee/fff")
#OUTPUT: /bbb/xxx/ddd/eee/fff
PySaad
  • 1,052
  • 16
  • 26
0

Almost the same question has been asked already here. In your case the answer would look like this:

for line in fileinput.input('file.txt', inplace=True):
    print(re.sub(r'(ccc)', 'xxx', line), end='')

See above link to learn about alternatives and efficiency. (Also note the quotes around file.txt)

Short explanation:

  • print()in Python prints lines with a newline character by default. To prevent this, end='' needs to be specified as keyword argument.
  • r'(ccc)' contains a pair of group parentheses which is not necessary in your case, so you can simply write r'ccc' as already pointed out by the two previous posts.
HHFox
  • 311
  • 2
  • 7