python,自己编写的第一个工作应用程序,实现对文本文件的计算并格式化另存为另一个文件

问题:现有一个文本文件evt_num.txt,文件内容如下:

1999-7-15    1  
1999-8-15    1   
1999-9-15    5   
1999-10-15    4 
1999-11-15    3 
1999-12-15    0 

需求:将文件增加一列,第3列内容为第2列内容的累加值,即c3[0]= 1,c3[1]=2,c3[2]=7,c3[3]=9......

具体实现代码如下:

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()

执行代码后生成一个新文件new_evt_num.txt,内容如下:

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

该段代码并不难理解,主要应用了文件读写操作,字符串分割,列表操作,字符串拼接等.

猜你喜欢

转载自www.cnblogs.com/iceberg710815/p/12045157.html