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

时间:2019-10-02 09:57:40

标签: 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                                           
                                       ContentType='text/csv',
                                       Body=final_data)

我想要的是用EndpointName替换另一行。考虑到SO问题Search and replace a line in a file in Python,我已经对此进行了编码:

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行,该行被转换为注释。 如果我在\n的末尾引入一个subst字符,它将删除ContentType行。我该怎么解决?

2 个答案:

答案 0 :(得分:1)

您在行尾忘记了\n

subst = "        response = runtime.invoke_endpoint(EndpointName='xgboost-otro', #Endpoint mark\n"

以及您的替换逻辑:

   new_file.write(subst)

答案 1 :(得分:1)

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

with open(file_path, 'r') as old_file:

另外,line.replace(line, subst)如此神秘地表达subst。无论如何,您都需要在subst的末尾添加换行符或使用

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

代替

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