像这样的东西:
with open('abc') as f, open('out.txt','w') as f2:
seen = False #initialize `seen` to False
for line in f: #iterate over each line in f
spl = line.split() #split the line at whitespaces
if seen: #if seen is True then :
spl[1] = '10' #set spl[1] to '10'
seen = False #set seen to False
line = " ".join(spl) + '\n' #join the list using `str.join`
elif not seen and spl[1] == '2': #else if seen is False and spl[1] is '2', then
seen = True #set seen to True
f2.write(line) #write the line to file
输出:
>>> print open('out.txt').read()
1 2 3 4 5
2 10 6 7 8
3 2 6 3 8
4 10 4 5 6
5 3 5 7 8
6 8 7 5 4
7 2 6 8 4
8 10 6 9 7