HTML模板,带有RAW CSV DATA:字段
<body>
<pre id="csv" style="display: none">
{{ RAW CSV DATA }}
</pre>
</body>
这个简短的教程展示了如何读取模板并呈现一个新的html,但没有展示如何将输出保存为另一个文件,例如";result.html";。
https://techmonger.github.io/69/jinja2-render-html/
当前使用Pandas处理RAW CSV数据并将其写入名为";test.csv":
import numpy as np
import pandas as pd
# Ticker data
input_file = 'tick.csv'
# Read csv input file Date, Adj_high, Adj_low into Pandas dataframe
df = pd.read_csv(input_file, usecols=[0,9,10],
parse_dates=['DATE'], date_parser = pd.to_datetime)
# Write DATE, ADJ_HIGH, ADJ_LOW to csv file
df.to_csv('test.csv', index=False)
文件";test.csv";包含原始CSV数据:
DATE,ADJ_HIGH,ADJ_LOW
2018-04-27,164.33,160.63
2018-04-30,167.26,161.84
2018-05-01,169.20,165.27
2018-05-02,177.75,173.80
2018-05-03,177.50,174.44
如果可能的话,如何使用Pandas将RAW CSV数据写入html模板?或者,如何使用Python/Pandas,无论是否使用Jinja2,读取test.csv文件并将其写入";预";标签?
生成的HTML文件如下所示:
<body>
<pre id="csv" style="display: none">
DATE,ADJ_HIGH,ADJ_LOW
2018-04-27,164.33,160.63
2018-04-30,167.26,161.84
2018-05-01,169.20,165.27
2018-05-02,177.75,173.80
2018-05-03,177.50,174.44
</pre>
</body>
正如Henry Ecker所评论的,没有位置参数的to_csv
只返回字符串,因此…
import jinja2
t = jinja2.Template('<pre>{{ raw_csv_data }}</pre>')
csv_data = df.to_csv(index=False)
html_string = t.render(raw_csv_data=csv_data)
此代码用于在csv数据中写入不带换行符的输出文件:
import jinja2
import pandas as pd
# AAPL EOD data file
input_file = 'AAPL.csv'
# Output File
output_file = 'jinja_test.html'
# Read csv input file Date, Adj_high, Adj_low into Pandas dataframe
df = pd.read_csv(input_file, usecols=[0,9,10],
parse_dates=[0], date_parser = pd.to_datetime)
t = jinja2.Template('<pre>{{ raw_csv_data }}</pre>')
csv_data = df.to_csv(index=False)
html_string = t.render(raw_csv_data=csv_data)
# Write result of render as html output file
with open(output_file, "w", newline='') as file:
file.write(html_string)