如何在 python 中替换文件中的未知值

How to replace unknown values inside a file in python

我找到了一个 10k+ 行的文件,其中有一些值,例如 image: "asdasddsg2332qh23h.png",我想用 image: ".png" 替换,但是 "" 之间有多个不同的值,所以我不能简单地以 "asdasddsg2332qh23h" 为目标并替换,因为这是 10k 组合中的 1 个,我想替换所有内容。有没有办法用 python 脚本实现这个?

这是我目前得到的:

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='')

按照@Barmar 的建议,使用正则表达式替换您的文本:

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))

FWIW 你甚至可能根本不需要 python,一个简单的 sed 命令会更快地完成这个技巧:

sed 's/.*\.png/.png/g' path_to_file > path_to_modified_file

或者如果你想就地修改:

sed -i 's/.*\.png/.png/g' path_to_file