對資料夾中所檔案(csv)進行讀寫操作
阿新 • • 發佈:2019-02-20
#coding=utf-8 #匯入csv包 #python版本為2.7 import csv import os #獲得當前目錄下的所有檔名字放入 current_dir=os.listdir(os.getcwd()) #尋找到需要操作的檔名 for folder_name in current_dir: if folder_name == "TPS_Aggregate": #切換目錄進入到要操作的檔案目錄下面 os.chdir(".\\TPS_Aggregate") sub_dir=os.listdir(os.getcwd()) #進入子資料夾,獲取每個子檔案的名字 for folder in sub_dir: path=".\\"+folder os.chdir(path) for filename in os.listdir(os.getcwd()): #獲取大檔案地址 tps_path=os.getcwd()+"\\"+filename avg_tps_path=os.getcwd()+"\\"+"AVG_"+filename tps=file(tps_path,"rb") tps_avg=file(avg_tps_path,"wb") #建立寫的檔案控制代碼 writer=csv.writer(tps_avg) #建立讀的檔案控制代碼 reader=csv.reader(tps) #建立一個數組,用來儲存CSV檔案的數字部分 number=[] #給期望的csv新增頭部資訊 writer.writerow(["Interface Name","AVG TPS","MAX TPS"]) #獲取原csv檔案的每一行資料 for line in reader: #獲取每行資料除去第一元素外的所有元素 for nu in line[1:len(line)-1]: #把list中為空的元素去掉 if nu!='': #把數字元素轉換為整形並加入number陣列 number.append(float(nu)) #把陣列number的最大值賦給bigd bigd=max(number) tps_sum=sum(number) #求平均值 avg_tps=tps_sum/len(number) #列印介面名稱和最大TPS print line[0],avg_tps,bigd #清空陣列中的元素,還原到初始化狀態 number=[] #把介面名稱和最大tps儲存到期望結果的CSV檔案中 writer.writerow([line[0],avg_tps,bigd]) #關閉CSV檔案,注意關閉順序 tps.close() tps_avg.close()