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

2024-05-29 04:51:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将字符串"$basetexturetransform" "center .5 .5 scale 4 4 rotate 0 translate 0 0"(包括引号)作为新行附加在包含字符串$basetexture的每一行下面

例如,文件

"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文件在一个文件夹中,我需要修改,这将是一个真正的痛苦,必须手动完成


Tags: 文件字符串文件夹translatecenterscalerotatemodular
1条回答
网友
1楼 · 发布于 2024-05-29 04:51:23

此表达式可能与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

相关问题 更多 >

    热门问题