Search code examples
pythonfileiopackagestringio

read string as a file using io.StringIO


I need to make a string to be read by bibtexparser's parsing_read. As far as I understood the module, it only reads file, not stream, so I have done:

text = "Some text"
with open("/tmp/bibtmp.bib", "w") as bibfile:
    bibfile.write(text)
self.parsing.parsing_read("/tmp/bibtmp.bib")

But, I am trying to make it read the string, and trying io.StringIO module as:

fakefile = io.StringIO("SomeText")
self.parsing.parsing_read(fakefile)

which is giving error(from the self.parsing.parsing_read, which opens the file):

TypeError: invalid file: <_io.StringIO object at 0x7fb4d6537ca8>

So, obviously, fakefile is io.StringIO, and not a Fakefile.

Am I understanding io.StringIO's purpose wrong? or just doing it wrong?


Solution

  • Based on the documentation from bibtexparser class, I think you should be using the .loads method, which returns a BibDatabase object from an input string or unicode. (This differs from the load method which does require a file object)

    https://bibtexparser.readthedocs.org/en/v0.6.2/_modules/bibtexparser.html#loads

    bibtexparser.loads(bibtex_str, parser=None)

    Load BibDatabase object from a string

    Parameters:

    • bibtex_str (str or unicode) – input BibTeX string to be parsed
    • parser (BibTexParser) – custom parser to use (optional)

    Returns:

    • bibliographic database object

    Return type:

    • BibDatabase