How to replace several different characters in text file using asterisk in python?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • yaron148
    New Member
    • Jan 2020
    • 1

    How to replace several different characters in text file using asterisk in python?

    I try to delete from text file those characters '{a}' '{b}' ... and so on (i have 250 curly braces in the text file) using this code:

    Code:
    # -*- coding: cp1255 -*-
    import sys,codecs,string
    
    reload(sys)
    sys.setdefaultencoding('utf8')
    root = r"G:\desktop\y\test2.txt"
    x = open(root)
    s=x.read().replace('{*}','').replace('-','')
    x.close()
    x=open(root,"w")
    x.write(s)
    x.close
    because the letters change in every curly brackets i used asterisk in the,

    but after i run this code nothing change in the text file:

    >>> =============== =============== == RESTART =============== =============== ==
    >>>
    >>>
    Last edited by gits; Jan 21 '20, 02:44 PM. Reason: added code tags
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    It's not clear what you are trying to do.

    Can you provide a minimum example of you filterfile (test2.txt), and and what you expect as output?

    Comment

    • SioSio
      Contributor
      • Dec 2019
      • 272

      #3
      How about using "re.sub"?
      Here is an example to delete characters '{a}' '{b}' '-'
      Code:
      import re
      text = "aaaaaa{a}-bbbbbbb{b}-ccccc{c}-dddddd{d}."
      text_mod = re.sub('\{[a-b]\}','',text).replace('-','')
      print (text_mod)
      result :aaaaaabbbbbbbc cccc{c}dddddd{d }.

      Comment

      Working...