常用轮子:text文本文件处理

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值