我有一个非常大的文本文件,我需要删除某个文本块。我要删除的文本从第452行开始,到第470行结束,它看起来像这样:
<ItemGroup>
<None />
<None Include="" />
<None Include="" />
<None Include="">
<LogicalName>Info.plist</LogicalName>
</None>
<None Include="" />
<None Include="" />
<None Include=" ">
<LogicalName>Info.plist</LogicalName>
</None>
<None Include="" />
<None Include="">
<LogicalName>Info.plist</LogicalName>
</None>
<None Include="Entitlements.plist" />
</ItemGroup>
我怎么能通过我的python脚本删除它?我试图做的是以下没有成功:
with open(os.path.join('folder', 'text.txt'),'r') as file:
content= file.readlines()
numb = 451
toadd=content[451:471]
for i in range(len(toadd)):
toadd[i] = toadd[i].replace(toadd[numb], '')
numb = numb +1
contout = content - toadd
with open(os.path.join('folder', 'text.txt'),'w') as out:
out.writelines(contout)
这里我尝试替换第452行和第470行中的每一行,但它不会改变文件中的任何内容。
如何删除文本文件中间的大文本块(彼此后约20行)?
答案 0 :(得分:1)
尝试此操作以删除您的文本块。如果行号与索引不匹配,您可能需要调整数字。
with open(os.path.join('folder', 'text.txt'),'r') as file:
content = file.readlines()
new_content = content[0:452] + content[471:]
with open(os.path.join('folder', 'new_text.txt'),'w+') as out:
out.writelines(new_content)