python 文件内容搜索、替换、添加

内容搜索

hello.txt 文件为:

hello world
hello python
hello China
#文件查找
import re   #引用re模块

f1  =  open("hello.txt","r")
content = f1.read()
print("输出文件内容:\n",content)      #输出文件内容
count = len(re.findall("hello",content)) 
#re.findall()返回的是一个列表

print("re.findall()的返回值: ",re.findall("hello",content))
print("共有{}个hello".format(count))

这里写图片描述

内容替换

f1 = open("hello.txt","r")
content = f1.read()
f1.close()

t = content.replace("hello","hi")
with open("hello.txt","w") as f2:
    f2.write(t)

替换后文件内容为:
这里写图片描述

删除空行

# coding = utf-8
def clearBlankLine():
    file1 = open('text1.txt', 'r', encoding='utf-8') # 要去掉空行的文件 
    file2 = open('text2.txt', 'w', encoding='utf-8') # 生成没有空行的文件
    try:
        for line in file1.readlines():
            if line == '\n':
                line = line.strip("\n")
            file2.write(line)
    finally:
        file1.close()
        file2.close()


if __name__ == '__main__':
    clearBlankLine()

这里写图片描述

  • 16
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值