python修改替换文件每行的指定字符

#简单的修改文件里的字符串
有个朋友经常要修改一大堆文件里指定字符的批量修改
所以写了下面一段代码:


filename =".\\modified.txt"
hand =str(input("前缀词:")).strip()
endwith =str(input("后缀词:")).strip()
change = str(input("要修改的整数初始值"))
filenamehand = open(filename,mode="r",encoding="utf-8")
newfilename = open("newfile.txt",mode='w+',encoding="utf-8")

def replacekey(hand,endwith,change):
	#读取一行,修改一行并写出newfile.txt文件
	for line in filenamehand:	#返回每行的索引和元素
		print(line)
		k=line.find(hand)
		j=line.find(endwith)
		if not(k==-1) and not(j==-1) :		#找到关键字在该行的索引起始位置
			hand1=line.find(hand)+len(hand)
			endwith1=line.find(endwith)
			x=line[:hand1]				#前缀行切割
			y=line[hand1:endwith1]		#中间切片
			z=line[endwith1:]			#提取尾部
			change = int(change)+1
			newy=y.replace(y,str(change))
			newfilename.write(x+newy+z)
			newfilename.flush()
		else:
			print("没有找到关键字")
			return False
	print("文件修改完成")


if 0==replacekey(hand,endwith,change)
filenamehand.close()
newfilename.close()
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值