插入带有Python的XML元素

2024-04-26 05:38:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个快速而肮脏的构建脚本,需要在一个小的xml配置文件中更新几行。由于文件太小,我使用一个公认的低效过程来更新文件,只是为了保持简单:

def hide_osx_dock_icon(app):
    for line in fileinput.input(os.path.join(app, 'Contents', 'Info.plist'), inplace=True):
        line = re.sub(r'(<key>CFBundleDevelopmentRegion</key>)', '<key>LSUIElement</key><string>1</string>\g<1>', line.strip(), flags=re.IGNORECASE)

    print line.strip()

这样做的目的是找到<key>CFBundleDevelopmentRegion</key>文本并在其前面插入LSUIElement内容。我在另一个地方做了类似的事情,效果很好,所以我想我只是错过了一些东西,但我看不到。你知道吗

我做错什么了?你知道吗


Tags: 文件keyre脚本appstring过程def
1条回答
网友
1楼 · 发布于 2024-04-26 05:38:44

您只打印最后一行,因为您的print语句在for循环之外:

for line in fileinput.input(os.path.join(app, 'Contents', 'Info.plist'), inplace=True):
    line = re.sub(r'(<key>CFBundleDevelopmentRegion</key>)', '<key>LSUIElement</key><string>1</string>\g<1>', line.strip(), flags=re.IGNORECASE)

print line.strip()

将该行缩进以匹配上一行:

for line in fileinput.input(os.path.join(app, 'Contents', 'Info.plist'), inplace=True):
    line = re.sub(r'(<key>CFBundleDevelopmentRegion</key>)', '<key>LSUIElement</key><string>1</string>\g<1>', line.strip(), flags=re.IGNORECASE)

    print line.strip()

相关问题 更多 >