如果使用python不存在,则在文本文件中添加一行

时间:2012-09-05 06:21:38

标签: python

  

可能重复:
  Add a line to a file if it not exist using python

我有一个文本文件如下:

  <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0">
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>

我想在之间添加一行<Import Project="$(ProjectName).targets" /> </ImportGroup></Project>如下

  <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0">
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
  <Import Project="$(ProjectName).targets" />
</Project>

我使用fileinput模块插入行但我不想添加 <Import Project="$(ProjectName).targets" />如果它已存在于文件中 我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

将文字作为文件的文字:

import re

match = = re.search( '\<ImportGroup Label="ExtensionTargets"\>', text )
text = text[:match.end()] +'<Import Project="$(ProjectName).targets" />\n'+ text[match.end():]

答案 1 :(得分:-1)

您应该读取整个文件或足够的行,并检查子字符串是否在内容中:

'<Import Project="$(ProjectName).targets" />' in file_content

或者您可以使用正则表达式使搜索更加健壮:

import re
regex = re.compile(r'<Import Project="\$\(ProjectName\)\.targets\s*/>')
if not regex.search(file_content):
    insert_line_into_file()
else:
    #the line already exists