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

  • A+
所属分类:Python学习

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

Python基础_文件操作实现全文或单行替换的方法!
下面小编就为大家带来一篇python基础_文件操作实现全文或单行替换的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧。

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

1、替换文本中的taste 为 tasting

1
2
3
4
5
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
1
2
3
4
5
6
7
8
9
10
#将文件读取到内存中
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、全文中搜索替换或者单行替换

1
2
3
4
5
6
7
8
9
10
#文本内容
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
taste
taste
taste
taste
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#定义一个函数,带有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,只替换匹配到的第一行

1
2
3
4
5
6
7
8
9
10
11
12
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)全局替换

1
2
3
4
5
6
7
8
9
10
11
12
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基础_文件操作实现全文或单行替换的方法就是小编分享给大家的全部内容了。

 

学习资料见知识星球。

以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。

快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利​​​​!

更多技巧, www.excelbook.cn

欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;

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

你将获得:

1、价值上万元的专业的PPT报告模板。

2、专业案例分析和解读笔记。

3、实用的Excel、Word、PPT技巧。

4、VIP讨论群,共享资源。

5、优惠的会员商品。

6、一次付费只需99元,即可下载本站文章涉及的文件和软件。

  • 我的微信
  • weinxin
  • 我的知识星球
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: