You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python fileinput替换内容时误删其他行,如何解决?

解决方法

问题出在使用fileinput的inplace=True模式时,只有通过print输出的内容会被写入目标文件,未被显式输出的行都会被丢弃。你只在匹配到目标行时执行了print,其他行没做输出处理,所以被全部删掉了。

正确的做法是循环处理每一行:匹配目标行时输出修改后的内容,不匹配时直接输出原行(注意加上end='',因为原行本身已经包含换行符,避免重复添加导致多余空行)。

修改后的脚本如下:

import fileinput

for line in fileinput.input("my_file.py", inplace=True):
    if line.startswith('output_folder ='):
        print("output_folder = '/new/file/path/'", end='')
    else:
        print(line, end='')

执行这个脚本后,my_file.py的内容会符合你的预期:

input_folder = 'bla/bla/'
output_folder = '/new/file/path/'
iterations = 20

内容的提问来源于stack exchange,提问作者NeStack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 05:12:39