替换文件 Python 中的 CSS 文本块

Replace CSS block of text within file Python

我打算制作一个 python 程序来帮助我对配置文件进行简单的编辑。我希望能够读取文件,替换文件的一部分,然后写入更改。我一直遇到的问题之一是有多条线是相同的。例如,配置文件如下所示:

/* Panel */

#panel {
    background-color: black;
    font-weight: bold;
    height: 1.86em;
}
#panel.unlock-screen,
#panel.login-screen {
    background-color: transparent;

有两行包含背景颜色:所以我无法测试该行是否等于字符串,因为如果我要替换包含背景颜色的每一行:我会得到不需要的更改。 此外,我不想依赖行的索引,因为随着配置文件行的添加或删除,它会发生变化。 如有任何帮助,我们将不胜感激!

您似乎正在尝试处理 CSS 个文件。要正确解析此文件格式,您需要类似 cssutils:

import cssutils

# Parse the stylesheet, replace color
parser = cssutils.parseFile('style.css')
for rule in parser.cssRules:
    try:
        if rule.selectorText == '#panel':
            rule.style.backgroundColor = 'blue'  # Replace background
    except AttributeError as e:
        pass  # Ignore error if the rule does not have background

# Write to a new file
with open('style_new.css', 'wb') as f:
    f.write(parser.cssText)

更新

我更改了代码,现在只更改 #panel

的背景