In Python 3, you can use the print function to write the data to a file (e.g. print('my data', file=my_open_file). This is well and good (and very cool). But can you print to a (string?) variable? If so, how?
In my specific use case, I am trying to avoid writing the data to a tempfile on disk just to turn and read that tempfile.
Edit: I'm can't just assign because my source data isn't a string, rather it's part of the html document tree as extracted by BeautifulSoup. Once I have the document tree extracted, I'm going to process it line by line.
My Code: (working now!)
with open("index.html", "r") as soup_file:
soup = BeautifulSoup(soup_file)
THE_BODY = soup.find('body')
not_file = io.StringIO()
print(THE_BODY, file = not_file) # dump the contents of the <body> tag into a file-like stream
with codecs.open('header.js', "w", "utf-8") as HEADER_JS:
for line in not_file2.getvalue().split('\n'):
print("headerblock += '{}'".format(line), file = HEADER_JS)
Better, Working Code:
with open("index.html", "r") as soup_file:
soup = BeautifulSoup(soup_file)
with codecs.open('header.js', "w", "utf-8") as HEADER_JS:
for line in str(soup.find('body')).split('\n'):
print("headerblock += '{}'".format(line), file = HEADER_JS)