Python 替换文件中的一行会将另一行移动到上级行

Python 替换文件中的一行会将另一行移动到上级行,python,regex,python-3.x,file,Python,Regex,Python 3.x,File,我有一个类似以下的py文件: final_data = ','.join(ordered_data.iloc[0].astype(str).values.tolist()) runtime = boto3.client('runtime.sagemaker') response = runtime.invoke_endpoint(EndpointName='xgboost-whatever', #Endpoint mark

我有一个类似以下的py文件:

final_data = ','.join(ordered_data.iloc[0].astype(str).values.tolist())
runtime = boto3.client('runtime.sagemaker')
response = runtime.invoke_endpoint(EndpointName='xgboost-whatever', #Endpoint mark                                           
                                       ContentType='text/csv',
                                       Body=final_data)
我想要的是用另一行的EndpointName替换该行。考虑到SO问题,我将其编码为:

def replace(file_path, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    with fdopen(fh,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                if re.search('response = runtime.invoke_endpoint(.*?)#Endpoint mark',line):
                    new_file.write(line.replace(line, subst))
                else:
                    new_file.write(line)
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)


file_path = '/home/whatever'
subst = "        response = runtime.invoke_endpoint(EndpointName='xgboost-otro', #Endpoint mark "

replace(file_path, subst)
但是,运行前面的代码会让我得到一些与我所寻找的不同的东西:

final_data = ','.join(ordered_data.iloc[0].astype(str).values.tolist())
runtime = boto3.client('runtime.sagemaker')
response = runtime.invoke_endpoint(EndpointName='xgboost-otro', #Endpoint mark                                                                              ContentType='text/csv',
                                       Body=final_data)
因此,我丢失了ContentType行,该行被转换为注释。
如果在
subst
的末尾引入
\n
字符,则会删除ContentType行。我该怎么解决呢?

您忘记了行末的
\n

subst = "        response = runtime.invoke_endpoint(EndpointName='xgboost-otro', #Endpoint mark\n"
在您的替换逻辑中:

   new_file.write(subst)

您需要以读取模式打开文件:

with open(file_path, 'r') as old_file:
另外,
line.replace(line,subst)
是一种非常隐晦的说法。您需要在
subst
的末尾添加一个换行符,或者使用

new_file.write("{}\n".format(subst)) 
而不是

new_file.write(line.replace(line, subst))

line.replace(line,subst)
是一种非常隐晦的说法。但是你需要添加一个换行符。使用
new\u file.write(“{}\n”.format(subst))
而不是
new\u file.write(line.replace(line,subst))
添加“r”解决了问题。谢谢做一个回答,这样我就可以接受它(当然,如果你愿意的话),因为内容类型行被删除了,这可能还不够。谢谢你的回答。正如我在问题中提到的,如果我这样做,那么当我尝试它时,整个ContentType行都会被删除,而不是删除它?你说的移除它是什么意思?你是说这行根本不会出现?没错,这就是我的意思,但在我的情况下,它没有删除它,而且它也不可能删除它?你确定吗?@CharifDZ但这会有所不同。我找不到上面的评论,因此无法解释,一旦找到,我将与大家分享。