我有一个带有ID
列的csv文件。我想知道是否有可能从我的数据框中获取每个ID值并将其另存为一个单独的html文件,其中ID值作为文件名,ID分配为该html文件中的变量。
my.csv
ID Name
1 ACME
2 EMCA
#and so on...
本地目录中所需的输出:
/path/to/my/1.html
/path/to/my/2.html
每个html文件都应声明ID变量和html模板:
<!DOCTYPE html>
<html>
<head>
<script>
var ID="1";
document.title = ID;
</script>
</head>
<body>
#I want to pass ID as a text and class in my html file
<div class='1'>My First 1</div>
<p>My first paragraph.</p>
</body>
</html>
到目前为止,我的代码:
import numpy as np
from pandas import *
import pandas as pd
data = pd.read_csv("/path/to/my.csv", quotechar='"')
for i in data['ID']:
id_filename = str(i)
data.to_html('/path/to/my/'+id_filename+'.html')
如何将HTML代码写入以ID值保存的HTML文件?
答案 0 :(得分:1)
像这样吗?
data = pd.read_csv("/path/to/my.csv", quotechar='"')
for ID in in data['ID']:
toWrite = f"""
<!DOCTYPE html>
<html>
<head>
<script>
var ID="{ID}";
document.title = ID;
</script>
</head>
<body>
#I want to pass ID as a text and class in my html file
<div class='{ID}'>My First {ID}</div>
<p>My first paragraph.</p>
</body>
</html>
"""
with open(f'/path/to/my/{ID}.html', "w") as file:
file.write(toWrite)