-1

I want to insert a string like this {% load static %} into the first line (at the very top) of existing html files through using python (by Beautifulsoup if possible). So from this:

<!DOCTYPE html>
<html>
<body>

</body>
</html>

I want the result to be like this. So i can run the python script and insert this line into all the existing html files i have.

{% load static %}
<!DOCTYPE html>
<html>
<body>
    
</body>
</html>
raven
  • 5
  • 1
  • 3

2 Answers2

1

You can use the insert_before() method to add a string before the DOCTYPE.

from bs4 import BeautifulSoup

html = '''
<!DOCTYPE html>
<html>
<body>
</body>
</html>
'''

soup = BeautifulSoup(html, "html.parser")

soup.contents[0].insert_before('{% load static %} \n')

print(soup.prettify())

Output:

{% load static %}
<!DOCTYPE html>
<html>
 <body>
 </body>
</html>
MendelG
  • 14,885
  • 4
  • 25
  • 52
-1

This might be what you are looking for here: Prepend line to beginning of a file you could just loop it and have it run for all the files you need to be updated.

Markwow
  • 141
  • 9