Python Forum

Full Version: Is it possible to update a CSS file from Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

I have a main.scss file (I'm using SASS) and a Jupyter Notebook (.ipynb) in the same folder. I want to update only ONE line of code in my main.scss file but I want to do it from my jupyter notebook's python code. Is this possible?

To illustrate, in my main.scss file I have this at the top:
$customer_color_1: #cb2324;

Using python, I ONLY want to update that $customer_color_1 variable to become as follows:
$customer_color_1: #005f9f;

Is this possible??? If so, how? Thank you for any help!!

-AL
css is just a text file!

Assuming: $customer_color_1: #cb2324; only appears 1 time, very easy.
Leave out the $, I think that will complicate matters! I think it is a reserved symbol.

myfile = '/path/to/mycss_files/my_css_file.css')
with open('path2mycssfile') as mycss:
    mystring = mycss.read()

newstring = mystring.replace('customer_color_1: #cb2324', 'customer_color_1: #005f9f')

with open('path2mycssfile', 'w') as mycss:
    mycss.write(newstring)
Otherwise, if you know the line number, also very easy.

linenr = 1
with open('path2mycssfile') as mycss:
    mylist = mycss.readlines()

# list numbering starts at 0
# line 1 is mylist[0]
my_line = linenr - 1 
the_line = mylist[my_line]
the_new_line = the_line.replace('customer_color_1: #cb2324', 'customer_color_1: #005f9f')
mylist[my_line] = the_new_line
mystring = ''.join(mylist)
with open('path2mycssfile', 'w') as mycss:
    mycss.write(mystring)
If the text you want to replace is present on more than 1 line, find all the lines with that text, then display them with line number, choose the line you want and replace.
(Apr-17-2022, 10:07 AM)Pedroski55 Wrote: [ -> ]css is just a text file!.

While this is true, the structure of it does have meaning. It would be better to use a library because

- it saves you having to write and maintain code that is likely not the thing you want to care about when writing your application,
- since a library is focused on a particular task, they'll do a better job than something hand rolled (better tested, catches errors, etc.),
One other thought - do you want your browser reload the css file after the change is made? If so, your next challenge will be to force that, and make sure it is not read from cache.
Very helpful, thanks so much guys!!