2

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)
3
  • 4
    Why would you not just assign instead? Commented Nov 25, 2014 at 22:27
  • @IgnacioVazquez-Abrams Maybe you want co capture the output of a function to a string that prints to a file. Commented Nov 25, 2014 at 22:32
  • 1
    I'm confused as to what the difference is between printing to a string and simply assigning a string. Isn't the end result the same in both cases? Commented Nov 25, 2014 at 22:34

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I like this approach, but this changes the 'storage block' from lines to chars. So see above for how I did it :)
As much as I appreciate the rep, now that I see what you are doing I have to agree with the others that just assigning to a variable is a much simpler solution. I had assumed you needed this for a more complicated reason.
You could have done a = str(soup.find('body')). print just calls str internally.
Thank you for explaining it all the way through. With all your pointers, many of the other comments now make sense, and I was able to simplify my code even more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.