從文字檔案製作html檔案

2021-10-01 08:12:13 字數 957 閱讀 4967

從文字檔案製作html檔案

#coding:utf-8

import webbrowser

import os

#"從文字檔案製作html檔案,忽略可能遇到的編碼錯誤"

rootdir = r"d:\諮詢\\"

i =0

for parent,dirnames,filenames in os.walk(rootdir)

:for filename in filenames:

if(filename[-3

:]=='txt'):

f =open

(rootdir + filename,

"r", encoding=

"utf-8"

, errors=

'ignore'

)#由於有時候會出現讀取失敗,所以忽略了讀取時遇到的錯誤

str0 = f.read(

) f.close

gen_html = r"d:\諮詢html\%s_24.html"

%(filename[:-

4])#開啟檔案,準備寫入

f =open

(gen_html,

'w', encoding=

"utf-8"

)# 寫入html介面中

message =

"""

%s"""

%(filename[:-

4],str0)

#寫入檔案

f.write(message)

#關閉檔案

f.close(

) i+=

1print

(i)

這段程式的缺點是原先文字中的換行符都都是了,所有的文字都成了一整段。encoding="utf-8"一定要加,不然預設gbk

將文字檔案轉為html檔案

前言 借助指令碼把文字裡的資料轉為html資料,此時用到cat cloud here document用法 如 info.txt文字資料為 zhangsan shang hai lisi beijing wangwu tianjin txt2html.sh指令碼 為 bin bash cat clo...

讀取文字檔案

void ctestdlg onreadinfo cfile filewrite1 testwrite1.txt cfile modecreate cfile modewrite cfile filewrite2 testwrite2.txt cfile modecreate cfile modew...

寫文字檔案

textoper 文字檔案操作類 public class textoper 新建乙個檔案 public bool createfile string strpath,string strname else file.create strpath strname return true catch ...