试试看效果是不是你想要的那种f = open('逐小时降水.txt',encoding='utf-8')
data = []
number = 0
for each_line in f:
temp = []
if each_line[:3] != "区站号":
(plot, year, mouth, day, time, num) = [i for i in each_line.split(' ') if i!='']
if plot == 'M1151':
temp.append(year)
temp.append(mouth)
temp.append(day)
temp.append(time)
if num == '/' or num == '/\n':
num = 0.0
temp.append(float(num))
data.append(tuple(temp))
# print(data)
new_data = []
for i in range(len(data)-1):
if data[i][0] == data[i+1][0] and data[i][1] == data[i+1][1] and data[i][2] == data[i+1][2]:
number += data[i][4]
continue
number += (data[i][4] + data[i+1][4])
new_data.append((data[i][0:3] + tuple((str(number),'')))[:-1])
number = 0
file_name = '日降水量' + '.txt'
tp_file = open(file_name, 'w',encoding='utf-8')
tp_file.write('{:^6}{:^6}{:^6}{:^10}\n'.format('年份','月份','日期','日降水量(mm)'))
for i in range(len(new_data)):
tp_file.write('{:^8}{:^8}{:^8}{:^10.2f}\n'.format(new_data[i][0],new_data[i][1],new_data[i][2],float(new_data[i][3])))
tp_file.close()
f.close()
|