在Python中的文本文件的特定行中附加数据?

use*_*340 1 python text file

假设我有这个文本文件:date.txt.一个月|天|一年

January|20|2014
February|10|
March|5|2013
Run Code Online (Sandbox Code Playgroud)

我想在二月| 10 |之后放入2012.我怎样才能做到这一点?

spi*_*lok 5

您需要将文件读入内存,修改所需的行并写回文件.

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')
Run Code Online (Sandbox Code Playgroud)

如果您不想使用临时文件:

with open('date.txt', 'rw') as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
        if line.startswith('February'):
            line[i] = line[i].strip() + '2012\n'
    f.seek(0)
    for line in lines:
        f.write(line)
Run Code Online (Sandbox Code Playgroud)