1. 程式人生 > >python 對txt中每行內容進行批量替換

python 對txt中每行內容進行批量替換

f = open('./val.txt')
lines = f.readlines() #整行讀取
f.close()
for line in lines:
    rs = line.rstrip('\n') #去除原來每行後面的換行符,但有可能是\r或\r\n
    newname=rs.replace(rs,'/JPEGImages/'+rs+'.jpg'+' '+'/SegmentationClassAug/'+rs+'.png')
    newfile=open('.val1.txt','a')
    newfile.write(newname+'\n')
    newfile.close()