mode1:
with open('a.txt',mode='rt',encoding='utf-8') as f:
res = f.read()
data = res.replace('aaa','111')
print(data)
with open('a.txt',mode='wt',encoding='utf-8') as f1:
f1.write(data)
mode2:
with open('a.txt',mode='rt',encoding='utf-8') as f,open('.a.txt.swap',mode='wt',encoding='utf-8') as f1:
for line in f:
f1.write(line.replace('aaa','111'))
os.remove('a.txt')
os.rename('.a.txt.swap','a.txt')