pythonpython-3.xflaskbacktrader

Easiest way to open an HTML file and save it as a string variable


I am working with a file in python and trying to save it to a string variable, so I can then pass it into an html file with Flask.

Here is the process:

  1. Run backtest and it saves the results as an HTML file.
  2. Take the the HTML file and set it to a string variable in python.
  3. Pass the string variable into HTML with flask (I know how to do this)

Here is the line of code that saves the file to the templates folder into backtest.html file. I can't change that process, what I want to do is then take that entire file, set it to a variable in python so I can then pass it with flask to a modal in an HTML file.

p = BacktraderPlotting(style='bar',barup='green',volume=False, lookback=200, filename="./templates/backtest.html", output_mode='save')

Solution

  • In order to set html file content to some variable, firstly you have to open it, read it and the assign it to a variable. To do that, you should use context manager as on below example:

    with open('path/to/file.html', 'r') as file:  # r to open file in READ mode
        html_as_string = file.read()
    

    If this is not the case, let me know.