简体   繁体   English

替换文件Python中的CSS文本块

[英]Replace CSS block of text within file Python

I'm tying to make a python program to help me make simple edits to a config file. 我想制作一个python程序来帮助我对配置文件进行简单的编辑。 I want to be able to read the file, replace a section of the file and then write the changes. 我希望能够读取文件,替换文件的一部分,然后写入更改。 One of the problems i have been having is that there are multiple lines that are the same. 我遇到的问题之一是有多条相同的线。 For example the config file looks like: 例如,配置文件如下所示:

/* Panel */

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

there are two lines that contain background-color: so i am unable to test if the line is equal to a string because if i were to replace every line containing background-color: i would get unwanted changes. 有两行包含background-color:所以我无法测试该行是否等于字符串,因为如果我要替换每一个包含background-color的行:我将得到不需要的更改。 Also I dont want to have to rely on the index of the line because as lines of the config file are added or removed, it will change. 我也不想依赖行的索引,因为随着配置文件的行被添加或删除,它将改变。 Any help would be appreciated! 任何帮助,将不胜感激!

It looks like you are trying to deal with CSS files. 看来您正在尝试处理CSS文件。 To properly parse this file format, you need something like cssutils : 要正确解析此文件格式,您需要使用诸如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)

Update 更新资料

I made a change in the code and now only change the background for #panel 我更改了代码,现在只更改了#panel的背景

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM