__author__ = 'Limaning'
# -*- coding: gbk -*-
#encoding=utf-8 注释可用中文
import os
import os.path #文件夹遍历函数
dirRoot = "f:\Python\\151220\maning1220"
listK = [53687,53882,53910,57014,57052,57071,57131]
listChangePath = [] #存储要修改的txt路径
listX = [] #存储其他所有txt路径
for parent,dirnames,filenames in os.walk(dirRoot):
for filepath in filenames:
txtPath = os.path.join(parent,filepath)
for txtChange in listK:
if txtPath[28:33] == str(txtChange):
listChangePath.append(txtPath)
else:
listX.append(txtPath)
print listChangePath
listM = list(set(listX))
listAll = [val for val in listM if val not in listChangePath]
print listAll
dirYear = "f:\Python\\151220\maning1220\\52765.txt"
yearList = []
y = open(dirYear)
for line in y:
m = line.strip()
dataLine = " ".join(m.split()) #将每行数据都改为一个空格
listData = dataLine.split(' ') #['2013', '4', '0']
yearList.append((listData[0],listData[1]))
y.close()
print yearList #用('1957', '7')这种元组作为key
#构造字典结构,将年份定义为字典的key,将对应值变为大的列表,其中再嵌套列表,形如: ('1999', '11'): [] 的形式
DataDic = {}
for yearTem in yearList:
DataDic[yearTem] = []
#print DataDic
for txtPath in listAll:
f = open(txtPath)
for line in f:
k = line.strip()
dataLine = " ".join(k.split()) #将每行数据都改为一个空格
listData = dataLine.split(' ') #['2013', '4', '0']
temK = (listData[0], listData[1])
DataDic[temK].append(listData[2])
f.close()
#print DataDic
#接下来 遍历字典DataDic,并将每个Key对应的值求平均值,并存储为普通的列表,生成txt文件
avgDic = {}
for keyTem in DataDic:
listStr = DataDic[keyTem]
listInt = map(int,listStr)
avgValue = sum(listInt)/len(listInt)
avgDic[keyTem] = avgValue
print avgDic
#依次打开listChangePath中的txt,从1957年开始检测,如果有数据 则用原数据,如果没有数据,则用avgDic的平均数据 新建txt
for changePath in listChangePath:
f = open(changePath) #打开txt文件
lastYear = int
for line in f:
m = line.strip()
dataLine = " ".join(m.split()) #将每行数据都改为一个空格
listData = dataLine.split(' ') #['2013', '4', '0']
lastYear = listData[0]
break
print lastYear #找出最后的年份
fileName = changePath[28:33] + "new" +".txt" #规定新文件的文件名
k = open(fileName,'a')
for yearNew in range(1957,int(lastYear)):
for month in range(1,13):
uTem = (str(yearNew),str(month))
avgValue = str(avgDic[uTem])
lineNew = str(yearNew)+' '+str(month)+' '+avgValue
k.write(lineNew)
k.write('\n')
for line in f:
m = line.strip()
dataLine = " ".join(m.split()) #将每行数据都改为一个空格
k.write(dataLine)
k.write('\n')
k.close()
f.close()
写的冗长,不够好。
写的冗长,不够好。