如果文件不存在,则使用 python 在文件中添加一行 [英] Add a line to a file if it not exist using python

查看:21
本文介绍了如果文件不存在,则使用 python 在文件中添加一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文件如下:

I have an xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
  <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"/> 之间添加一行如下

I want to add a line <Import Project="$(ProjectName).targets" /> between </ImportGroup> and </Project> as follows

<?xml version="1.0" encoding="utf-8"?>
  <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>

如果行 已经存在于文件中,则无需添加.

If the line <Import Project="$(ProjectName).targets" /> already exists in file there is no need to add.

我该怎么做?

推荐答案

您的问题是基于文本文件中的行,但输入文件显然是 XML,因此假设您实际上想要添加一个导入(如果它不存在),试试这个:

Your question is based on lines in text files, but the input file is clearly XML, so assuming you actually want to add an Import if it doesn't exist, try this:

import xml.dom.minidom

importstring = "$(Projectname).targets"
filename = "test.xml"

tree = xml.dom.minidom.parse(filename)
Project = tree.getElementsByTagName("Project")[0]

for Import in Project.getElementsByTagName("Import"):
    if Import.getAttribute("Project") == importstring:
        break
else: # note this is else belongs to the for, not the if
    newImport = xml.dom.minidom.Element("Import")
    newImport.setAttribute("Project", importstring)
    Project.appendChild(newImport)

tree.writexml(open(filename, 'w'))

这篇关于如果文件不存在,则使用 python 在文件中添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆