用多行替换字符串或空白(如果没有)

我有几行代码应该用包含多行的变量替换字符串,如果变量不包含任何内容,则只需将字符串替换为空白


我当前具有应替换字符串的文件看起来像


"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 替换文件中的字符串时,它只输出一行。如果变量中没有任何内容,我如何设法将它们全部添加到文件中或将其替换为空白。


电流输出示例:


"resources": [

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

]


慕娘9325324
浏览 141回答 1
1回答

慕神8447489

迭代文件对象会产生文件的每一行,因此您的循环变量lines在任何给定时间都包含文件的一行。每次通过循环,您都会resourceslist用 的当前值覆盖 的内容lines,因此最后它包含文件的最后一行。如果缩进无关紧要,您可以只设置resourceslist = f.read()而不是循环。如果您希望资源文件的每一行都以与 stringtobereplaced 相同的方式缩进,则您将不得不对模板文件进行更复杂的处理(可能匹配像 "^(?P.*)stringtobereplaced 这样的正则表达式" 并在每个资源行前加上匹配对象的“前缀”组)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python