Python - 在包含特定字符串的另一行下追加行

Python - Append line under another line that contains a certain string

我想在包含字符串 $basetexture.

的每一行下方附加字符串 "$basetexturetransform" "center .5 .5 scale 4 4 rotate 0 translate 0 0"(包括引号)作为新行

例如,文件

"LightmappedGeneric"
{
    "$basetexture" "Concrete/concrete_modular_floor001a"
    "$surfaceprop" "concrete"
    "%keywords" "portal"
}

变成

"LightmappedGeneric"
{
    "$basetexture" "Concrete/concrete_modular_floor001a"
    "$basetexturetransform" "center .5 .5 scale 4 4 rotate 0 translate 0 0"
    "$surfaceprop" "concrete"
    "%keywords" "portal"
}

并且我想对文件夹(包括子文件夹)中具有文件扩展名“.vmt”的每个文件执行此操作。

在 Python 中有没有简单的方法来做到这一点?我在一个文件夹中有大约 400 .vmt 个文件需要修改,如果必须手动修改,那将是一件非常痛苦的事情。

这个表达式可能会用 re.sub:

import re

regex = r"(\"$basetexture\".*)"

test_str = """
"LightmappedGeneric"
{
    "$basetexture" "Concrete/concrete_modular_floor001a"
    "$surfaceprop" "concrete"
    "%keywords" "portal"
}
"LightmappedGeneric"
{
    "$nobasetexture" "Concrete/concrete_modular_floor001a"
    "$surfaceprop" "concrete"
    "%keywords" "portal"
}

"""

subst = "\1\n\t\"$basetexturetransform\" \"center .5 .5 scale 4 4 rotate 0 translate 0 0\""

print(re.sub(regex, subst, test_str, 0, re.MULTILINE))

输出

"LightmappedGeneric"
{
    "$basetexture" "Concrete/concrete_modular_floor001a"
    "$basetexturetransform" "center .5 .5 scale 4 4 rotate 0 translate 0 0"
    "$surfaceprop" "concrete"
    "%keywords" "portal"
}
"LightmappedGeneric"
{
    "$nobasetexture" "Concrete/concrete_modular_floor001a"
    "$surfaceprop" "concrete"
    "%keywords" "portal"
}

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


参考

Find all files in a directory with extension .txt in Python