Question: an existing text file evt_num.txt, document reads as follows:
1999-7-15 1
1999-8-15 1
1999-9-15 5
1999-10-15 4
1999-11-15 3
1999-12-15 0
Demand: increases file a third column contents of the accumulated value of the second column contents, i.e. c3 [0] = 1, c3 [1] = 2, c3 [2] = 7, c3 [3] = 9 .. ....
Specific codes are as follows:
f1 = open('evt_num.txt','r') f2 = open('new_evt_num.txt','w') c1 = [] c2 = [] C3 = [] count = 0 s = 0 for i in f1: x,y,z = i.strip().split() c1.append(x) c2.append(y) s += int(y) c3.append(s) line = str(c1[count])+'\t'+str(c2[count])+'\t'+str(c3[count])+'\n' f2.write(line) count += 1 f1.close() f2.close()
After executing the code to generate a new file new_evt_num.txt, as follows:
1999-7-15 1 1
1999-8-15 1 2
1999-9-15 5 7
1999-10-15 4 11
1999-11-15 3 14
1999-12-15 0 14
This code is easy to understand, the main application file read and write operations, string segmentation, list operations, string concatenation like.