Search code examples
pythontext-processing

How to replace unknown values inside a file in python


I go a file which is 10k+ rows and there are values such as image: "asdasddsg2332qh23h.png" which I want to replace with image: ".png" but there are multiple different value between the "" so I can't simply target "asdasddsg2332qh23h" and replace as that is 1 out of 10k combination and I want to replace everything. Is there a way of achieving this with a python script?

This is what I got so far:

import fileinput

replace_texts = {'test': 'w/e'}

for line in fileinput.input('readme.json', inplace=True):
    for search_text in replace_texts:
        replace_text = replace_texts[search_text]
        line = line.replace(search_text, replace_text)
    print(line, end='')

Solution

  • As suggested by @Barmar, use a regex to replace your text:

    import re
    
    PAT = re.compile('image: ".*\.png"')
    with open('readme.json') as inp, open('output.json', 'w') as out:
        for line in inp:
            out.write(PAT.sub('image: ".png"', line))