python 中怎么替换字符串

Python022

python 中怎么替换字符串,第1张

Python替换某个文本中的字符串,然后生成新的文本文档,代码如下:import osos.chdir('D:\\') # 跳到D盘if not os.path.exists('test1.txt'): # 看一下这个文件是否存在exit(-1) #不存在就退出lines = open('test1.txt').readlines() #打开文件,读入每一行fp = open(''test2.txt','w') #打开你要写得文件test2.txtfor s in lines:# replace是替换,write是写入fp.write( s.replace('love','hate').replace('yes','no'))fp.close() # 关闭文件

读文件的模式有很多种不一一列举,r+表示打开一个文件用于读写。文件指针将会放在文件的开头。

def readFile(path):

#R

with open(path,"r+") as f:

for line in f:

print(line)

f.close()

print("读文件完成")

path="D:\\tmp\\manim\\file\\1.txt"

readFile(path)

查找字符串位置,str.find(target) 返回起始点位置如果是-1则表示不存在

"123WWW".find("WWW")

文件指针偏移到指定位置

#文件路径,原字符串,要替换成的目标字符串

def replaceText(filePath,sourceText,targetText):

if(len(sourceText)!=len(targetText)):

raise Exception("原始字符串长度与目标字符串不符,容易覆盖有用信息", sourceText,targetText)

with open(filePath,'r+') as f:

line=f.readline()

index=0

# 遇到中间空行的可以自行观察并不是空字符串

while ( line!=""):

print(line)

# 本行内字符串所在位置

windex=line.find(sourceText)

if(windex!=-1):

print("windex={}".format(windex))

print("当前位置:{},替换内容起点:{}".format(f.tell(),index+windex))

f.seek(index+windex)

f.write(targetText)

# f.flush()

f.seek(index)

# 返回当前文件指针,应该是新一行的开始位置

index=f.tell()

line=f.readline()

f.close()

print("文件修改完毕")