使用该行的模式替换整行

时间:2018-04-04 11:58:57

标签: python replace

我有一个文本文件:

#define PUBLICATION_URI_VALUE_DELL                          "http://downloads.dell.com/redfish/bmc/schemas"
#define MAX_NUM_JSON_SCHEMAS                263
#define MAX_JSONFILE_LENGTH                 64
#define ODATA_CONTEXT_VALUE_JSONSCHEMA_FILE_COLLECTION          METADATA_URI "#" JSONSCHEMA_URISEGMENT
#define ODATA_TYPE_VALUE_JSONSCHEMA_FILE_COLLECTION             "#JsonSchemaFileCollection.JsonSchemaFileCollection"
#define NAME_VALUE_JSONSCHEMA_FILE_COLLECTION                   "Schema Repository"

现在我的问题是如何在运行时替换此行263中的#define MAX_NUM_JSON_SCHEMAS 263

我试过这个:

import os
import sys

old="#define MAX_NUM_JSON_SCHEMAS"
with open("MetadataProvider.h","r+") as myfile:
    for line in myfile:
        if old in line:
            myfile.write(line.replace(line,"#define MAX_NUM_JSON_SCHEMAS 356"))

1 个答案:

答案 0 :(得分:1)

使用单独的处理程序来读取和写入文件。

<强>实施例

with open(r"MetadataProvider.h", "r") as infile:
    res = []
    for i in infile:
        if i.strip().startswith("#define MAX_NUM_JSON_SCHEMAS"):
            res.append("#define MAX_NUM_JSON_SCHEMAS        356")
        else:
            res.append(i.strip())

with open(r"MetadataProvider.h", "w") as outfile:
    for i in res:
        outfile.write(i+"\n")