0

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!

3
  • You could use more check statements depending upon the surrounding text of variable you want to change. Commented May 20, 2015 at 21:01
  • 3
    What edits do you want to make, what differentiates those two lines, etc.? Commented May 20, 2015 at 21:01
  • 1
    In this example, which of the two lines is the one that you want to replace? What's the general criterion? Commented May 20, 2015 at 21:30

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

This may work, in terms of my example, how do I know if I'm changing the background of #panel {}
See the update. In general, you can experiment for yourself by trying out the code in the interpreter. I did not know anything about cssutils until now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.