Manoj G
Manoj G

Reputation: 1796

Is it possible to insert some text in a specified location of a file?

I want to write a code to insert a text file which contains some set of codes which have to be inserted in the Head section of a HTML file. I don't want to do it manually since i have 100s of HTML files in a folder.

Is it possible to tell my code to search for the Head tag and append the given text file below that?

How can we do this?

Upvotes: 0

Views: 210

Answers (2)

Schuh
Schuh

Reputation: 1095

Since you read in html, i would recommend doing this with ElementTree which works somewhat like this:

import xml.etree.ElementTree as etree

html = etree.parse(file_path)
head = html.getroot().find('head')
# To insert a tag surrounding in <head>:
newtag = etree.Element("newtag", attrib={})
newtag.text = "Text inside newtag surrounding"
head.insert(0,newtag)
# To just insert a text inside the head tag surrounding:
head.text = newtext + head.text
html.write(new_file_path)

See ElementTree documentation for Python2 or Python3

Upvotes: 1

jitendra
jitendra

Reputation: 1458

If you can use sed, this might be a solution you can consider:

for file in *.html; do sed -i.bak '/<head>/a\ADD YOUR TEXT HERE' $i; done

This will write 'ADD YOUR TEXT' to the line next to line containing <head> tag. Your original files will have an added extension .bak.

PS: If your original files are complex and do not contain properly formatted html or the text that you want to add is complex, you should use BeautifulSoup or some specialized library that deal with markup language.

Upvotes: 2

Related Questions