Search code examples
pythonmarkdownstringio

Is there any advantage to using BytesIO with markdown instead of open / read in Python?


Considering the following code:

from markdown import markdown

f = open('myfile.md', 'r')
html_text = markdown(f.read())
f.close()

Is there any speed advantage or disadvantage to using io.BytesIO and markdownFromFile? Or is it a wash?

from markdown import markdownFromFile
from io import BytesIO

s = BytesIO()
markdownFromFile(input='myfile.md', output=s)
html_text = s.getvalue()
s.close()

Thanks in advance for any information.


Solution

  • It would be best if you benchmark it yourself, but just from the looks of it I don't see any advantage of using BytesIO. Instead of reading the file and parsing it directly into a string, you'd be first reading and processing it into a BytesIO object and then using BytesIO.getvalue to get the string you need.

    The former also is easier to read. Could be made even simpler with:

    with open('myfile.md', 'r') as f:
        html_text = markdown(f.read())