您需要将文件读入内存,修改所需的行并写回文件。
temp = open('temp', 'wb')with open('date.txt', 'r') as f: for line in f: if line.startswith('February'): line = line.strip() + '2012n' 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() + '2012n' f.seek(0) for line in lines: f.write(line)


