将文件的每行读取到字典中

文件每行内容格式为:

cui:123456789


f = open('user.txt')
d = f.readlines()
f.close()
mydict = {}
for i in d:
    user = i.split(':')[0]
    info = i.split(':')[1].rstrip()
    mydict[user] = info


替换匹配行的指定字符串

将test.txt中的zhang修改为cui

import re
import os
f=open("test.txt", "r+")
    forline inf.readlines():
    if line.find("zhang") >=0:
        s =line.replace("zhang", "cui")
        f.writelines(s)