总述
嵌入式端做webserver时,一般将html文件保存到一个数组里,此时就需要对html文件的内容进行转换了。
具体实现
编程语言:Python
主要API介绍:
os.path.dirname 获取一个路径的路径名
os.path.basename 获取文件名
os.path.join 连接路径目录加文件名
open 打开文件
replace 替换字符
import os
import sys
def html_toarray(html_path):
"""
:param html_path: html的路径
:return: NULL
"""
save_c_array_path = os.path.join(os.path.dirname(html_path),os.path.basename(html_path).split(".")[0] + ".h") #保存数组的路径
print(save_c_array_path)
with open(html_path, "r", encoding='UTF-8') as f:
nlines = f.readlines()
string_splite = []
for i in nlines:
i = i.strip() #除首尾空格
if len(i) > 0:
i = i.replace("\\", "\\\\").replace("\"", "\\\"").replace('\n', '') # 替换" 替换\
i = i + "\\r\\n\\"
string_splite.append(i)
with open(save_c_array_path, "w", encoding='UTF-8') as f:
f.write("static const char c_array[] = { \"\\\n")
for i in string_splite:
f.write(i + "\n")
f.write("\"};")
print("convert successed\r\n")
html_toarray(r"xxxxxxxxxxxx")