Python学习---第十七天

来源:互联网 发布:qq飞车数据 编辑:程序博客网 时间:2024/05/21 16:10

在下这厢有礼了

练习

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

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 tonguetastetastetastetaste

#定义一个函数,带有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 tonguetastetastetastetaste


2)全局替换


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




原创粉丝点击