我有一个文本文件:
#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"))
答案 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")