Reputation: 706
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)
Upvotes: 2
Views: 14264
Reputation: 48725
UPDATED RESPONSE BASED ON UPDATED QUESTION
If all you need to do is convert your object as a string, simply call the str
function on the variable... this is what print
does internally.
a = str(soup.find('body'))
Calling print
does a whole bunch of other stuff that you don't need if all you need is a string representation.
ORIGINAL RESPONSE
You can use io.StringIO.
import io
f = io.StringIO()
print('my data', file=f)
# to get the value back
a = f.getvalue()
print(a)
f.close()
Note that on python2 this is under StringIO.StringIO
.
This solution is good for when you have pre-existing code that wants to print to file, but you would rather capture that output in a variable.
Upvotes: 7