我有幾行代碼應該用包含多行的變量替換字符串,如果變量不包含任何內容,則只需將字符串替換為空白我當前具有應替換字符串的文件看起來像"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",]
1 回答

慕神8447489
TA貢獻1780條經驗 獲得超1個贊
迭代文件對象會產生文件的每一行,因此您的循環變量lines
在任何給定時間都包含文件的一行。每次通過循環,您都會resourceslist
用 的當前值覆蓋 的內容lines
,因此最后它包含文件的最后一行。
如果縮進無關緊要,您可以只設置resourceslist = f.read()
而不是循環。如果您希望資源文件的每一行都以與 stringtobereplaced 相同的方式縮進,則您將不得不對模板文件進行更復雜的處理(可能匹配像 "^(?P.*)stringtobereplaced 這樣的正則表達式" 并在每個資源行前加上匹配對象的“前綴”組)。
添加回答
舉報
0/150
提交
取消