将字符串替换为多行,如果不是,则为空

2024-10-08 19:22:32 发布

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

我有几行代码,应该用包含多行的变量替换字符串,如果变量不包含任何内容,那么就用空白替换字符串

我的当前文件中包含应替换的字符串

"resources": [
        stringtobereplaced
    ]

我现在的代码是

with open('filepaths', "r+") as f:
            for _ in range(1):
                next(f)
            for lines in f:
                resourceslist = lines
                print(resourceslist)
        os.chdir(base_dir)
        with open(unique_filename) as f:
            newText=f.read().replace('stringtobereplaced', resourceslist)
        with open(unique_filename, "w") as f:
            f.write(newText)

变量resourceslist中包含以下内容

"/home/django/copypaste/cleanup/var/media/admin/9514a8e4-8ad8-4917-a162-6d618b6616d3/splash279/lib/props/barbershop_pole.blend",
"/home/django/copypaste/cleanup/var/media/admin/9514a8e4-8ad8-4917-a162-6d618b6616d3/splash279/lib/props/hairdryer.blend",
"/home/django/copypaste/cleanup/var/media/admin/9514a8e4-8ad8-4917-a162-6d618b6616d3/splash279/lib/chars/pigeon.blend",
"/home/django/copypaste/cleanup/var/media/admin/9514a8e4-8ad8-4917-a162-6d618b6616d3/splash279/lib/chars/agent.blend",
"/home/django/copypaste/cleanup/var/media/admin/9514a8e4-8ad8-4917-a162-6d618b6616d3/splash279/lib/nodes/nodes_shaders.blend",
"/home/django/copypaste/cleanup/var/media/admin/9514a8e4-8ad8-4917-a162-6d618b6616d3/splash279/tools/camera_rig.blend",

但是当我用变量resourceslist替换文件中的字符串时,它只输出一行。如果变量中没有任何内容,如何将它们全部添加到文件中,或者用blank替换

电流输出示例:

"resources": [
    "/home/django/copypaste/cleanup/var/media/admin/089a4bd9-a618-41bd-a09b-f3616c773199/splash279/tools/camera_rig.blend",
]

Tags: 文件django字符串homeadminvarlibwith
1条回答
网友
1楼 · 发布于 2024-10-08 19:22:32

迭代一个file对象会产生文件的每一行,因此循环变量lines在任何给定的时间都包含文件的一行。每次通过循环时,您都会用当前值lines覆盖resourceslist的内容,因此最后它包含文件的最后一行

如果缩进不重要,可以设置resourceslist = f.read()而不是循环。如果您希望资源文件的每一行都以stringtobereplace相同的方式缩进,则必须对模板文件进行更复杂的处理(可能需要匹配regex,如“^(?P.*)stringtobereplace”,并在每个资源行前面加上match对象的“prefix”组)

相关问题 更多 >

    热门问题