#简单的修改文件里的字符串
有个朋友经常要修改一大堆文件里指定字符的批量修改
所以写了下面一段代码:
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()