问题
I'm tying to make a python program to help me make simple edits to a config file. 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. 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!
回答1:
It looks like you are trying to deal with CSS files. To properly parse this file format, you need something like 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
来源:https://stackoverflow.com/questions/30360290/replace-css-block-of-text-within-file-python