python基础_文件操作实现全文或单行替换的方法

yipeiwu_com5年前Python基础

python修改文件时,使用w模式会将原本的文件清空/覆盖。可以先用读(r)的方式打开,写到内存中,然后再用写(w)的方式打开。

1、替换文本中的taste 为 tasting

Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
#将文件读取到内存中
with open("./fileread.txt","r",encoding="utf-8") as f:
 lines = f.readlines() 
#写的方式打开文件
with open("./fileread.txt","w",encoding="utf-8") as f_w:
 for line in lines:
  if "taste" in line:
   #替换
   line = line.replace("taste","tasting")
  f_w.write(line)

2、全文中搜索替换或者单行替换

#文本内容
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
taste
taste
taste
taste
#定义一个函数,带有4个参数
#x 表示要更新的文件名称
#y 表示要被替换的内容
#z 表示 替换后的内容
#s 默认参数为 1 表示只替换第一个匹配到的字符串
# 如果参数为 s = 'g' 则表示全文替换
def string_switch(x,y,z,s=1):
 with open(x, "r", encoding="utf-8") as f:
  #readlines以列表的形式将文件读出
  lines = f.readlines()
 
 with open(x, "w", encoding="utf-8") as f_w:
  #定义一个数字,用来记录在读取文件时在列表中的位置
  n = 0
  #默认选项,只替换第一次匹配到的行中的字符串
  if s == 1:
   for line in lines:
    if y in line:
     line = line.replace(y,z)
     f_w.write(line)
     n += 1
     break
    f_w.write(line)
    n += 1
   #将剩余的文本内容继续输出
   for i in range(n,len(lines)):
    f_w.write(lines[i])
  #全局匹配替换
  elif s == 'g':
   for line in lines:
    if y in line:
     line = line.replace(y,z)
    f_w.write(line)

测试

1)默认参数 1,只替换匹配到的第一行

string_switch("fileread.txt","taste","tasting")
 
#结果
Yesterday when I was young
昨日当我年少轻狂
The tasting of life was sweet
生命的滋味是甜的
As rain upon my tongue
taste
taste
taste
taste

2)全局替换

string_switch("fileread.txt","taste","tasting","g")
 
#结果
Yesterday when I was young
昨日当我年少轻狂
The tasting of life was sweet
生命的滋味是甜的
As rain upon my tongue
tasting
tasting
tasting
tasting

以上这篇python基础_文件操作实现全文或单行替换的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈终端直接执行py文件,不需要python命令

然后给脚本文件运行权限, 方法(1)chmod +x ./*.py 方法(2)chmod 755 ./*.py (777也无所谓啦) 这个命令不去调整,会出现permission den...

python创建学生成绩管理系统

python创建学生成绩管理系统

python学生成绩管理系统创建,供大家参考,具体内容如下 要求编写学生类,班级类,并在电脑运行生成表单,输入一个数字,得到对应的结果。 输出样式 代码如下 学生类 class S...

使用Python paramiko模块利用多线程实现ssh并发执行操作

1.paramiko概述 ssh是一个协议,OpenSSH是其中一个开源实现,paramiko是Python的一个库,实现了SSHv2协议(底层使用cryptography)。 有了Pa...

Django安装配置mysql的方法步骤

Django安装配置mysql的方法步骤

近期做那个python的开发,今天就来简单的写一下Django安装配置mysql的方法步骤 安装mysql 首先安装pymysql pip install pymysql 然后安装...

django drf框架中的user验证以及JWT拓展的介绍

登录注册是几乎所有网站都需要去做的接口,而说到登录,自然也就涉及到验证以及用户登录状态保存,最近用DRF在做的一个关于网上商城的项目中,引入了一个拓展DRF JWT,专门用于做验证和用户...