temp = open('temp', 'wb')
with open('date.txt', 'r') as f:
for line in f:
if line.startswith('February'):
line = line.strip() + '2012\n'
temp.write(line)
temp.close()
shutils.move('temp', 'data.txt')
如果您不想使用临时文件:
with open('date.txt', 'r+') as f: #r+ does the work of rw
lines = f.readlines()
for i, line in enumerate(lines):
if line.startswith('February'):
lines[i] = lines[i].strip() + '2012\n'
f.seek(0)
for line in lines:
f.write(line)