import os
import glob
class Class_Util_Text():
def __init__(self):
pass
def read_text(self,text_path):
"""
读取本地text文件到列表,并返回该列表
"""
assert os.path.exists(text_path)
with open(text_path,"r") as f:
lines=f.readlines() #读行
return lines
def write_text(self,text_path,text_content):
"""
把文字写入文本文件中,会清空文本文件的原有内容
"""
with open(text_path,"w") as f:
f.writelines(text_content)
f.writelines("\n")
def append_text(self,text_path,text_content):
"""
把文字添加到文本文件的末尾,保留原文本文件内容
"""
with open(text_path,"a") as f:
f.writelines(text_content)
f.writelines("\n")
def replace_text(self,text_path,replace_old,replace_new):
"""
替换文本文件中的部分文字,先读文件,替换文字后,再重新写入文件
"""
#read
with open(text_path,"r") as f:
lines=f.readlines()
data=[]
for i in lines:
#根据条件修改
if(replace_old in i):
i=i.replace(replace_old,replace_new) #修改 replace_old 为 replace_new
data.append(i) #记录每一行
#write
with open(text_path,"w") as f:
for i in data:
f.writelines(i)
if __name__ =="__main__":
txt_obj = Class_Util_Text()
dir_path = "D:\pypi-packages\simple"
html_files = glob.glob(dir_path+"/*/index.html")
for html_path in html_files:
txt_obj.replace_text(html_path,replace_old="<a href='",replace_new="<a href='../../" )
# txt_obj.replace_text(html_path,replace_old="<a href='../../",replace_new="<a href='" )
lines = txt_obj.read_text(html_path)
print(html_path)
print(lines)
常用轮子:text文本文件处理
最新推荐文章于 2024-06-27 13:59:45 发布