def eachline(filename):
with open(filename, 'rt') as handle:
for lnno, line in enumerate(handle):
yield lnno, line
writeback = []
for line_no, line in eachline(filename):
if tobefind in line:
print tobefind+1
line = changeto+'\n'
writeback.append(line)
with open(filenamem, 'wt') as handle:
handle.writelines(writeback)
for eachline in lines:
if 'aaa' in eachline:
eachline = 'bbb'
最后将文件写回即可