如果值存在,我想替换奇数行,否则如果不存在,请添加它



我有一个示例文本文件,其中包含类似的数据

<iden/><provider></provider><trace>065110d4-cec5-d433772ed57a</trace>
<ServiceRQ>Some xml data</ServiceRQ>
<iden/><provider></provider>
<ServiceRQ>Some xml data</ServiceRQ>

像这样等等,它是一个相当大的文件。我想检查奇数行如果存在<trace>065110d4-cec5-43f9-b089-d433772ed57a</trace>,则将其替换为<trace>xyz</trace>,否则如果不存在<trace>065110d4-cec5-43f9-b089-d433772ed57a</trace>,则添加<trace>xyz</trace>我的代码:

with open("Sample_xml.txt", 'r') as fp:
output = fp.readlines()
type(output)
s = len(output) - 1
tc = 0
rq = 1
while (tc <= s) and (rq <= s):
if tc % 2 == 0:
a = (output[tc])
if a.find("<trace") != -1:
a = re.sub('(?<=<trace>)(.*?)(?=</trace>)','xyz', a)
print(a)
elif a.find("<trace>") == -1:
a = a.rstrip() + '<trace>xyz</trace>' +'n'
print(a)
if rq % 2 != 0:
b = (output[rq])
print(b)
with open("Fin_xml.txt", "a") as myfile:
myfile.write(a)
myfile.write(b + 'n')

tc += 2
rq += 2

该文件太大,超过了800mb,因此此代码无法正确使用readlines((。请有人帮我输入代码

如果我理解正确,您不想读取整个文件(但我不认为800mb有那么多(
在这种情况下,您可以使用next(fp)来逐个读取每一行,而不是fp.readlines()。若你们想跳过这一行,就做两次

还可以查看-读取python 中的大文件

正如@Archili Robakidze所指出的,您可以逐行读取一个大文件。这将确保存储器中只保留一行。

您还可以简化代码。使用enumerate获取行号。由于文件中的第一行是line 1而不是line 0,请使用enumerate(fp, 1):

import re
with open("Sample_xml.txt", 'r') as fp:
for i, line in enumerate(fp, 1):
# If the line number is odd, do the check and replace
if i%2 != 0:
if line.find("<trace") != -1:
line = re.sub('(?<=<trace>)(.*?)(?=</trace>)','xyz', line)
print(line)
elif line.find("<trace>") == -1:
line = line.rstrip() + '<trace>xyz</trace>' +'n'
print(line)
with open("Fin_xml.txt", "a") as myfile:
myfile.write(line)

相关内容

最新更新