python 讀取txt文件到excelc

需求:一個文件夾下的txt文件谢揪,并計算每N(3)行數(shù)據(jù)為平均值蕉陋,結果需要轉換成excel,輸出到不同的列拨扶。

原始數(shù)據(jù):(結構構成)
1321,214124,214124
32423,324525,235
2141,2154124,2132134
1321,214124,214124
32423,324525,235
2141,2154124,2132134
輸出結果:(結構構成)

x y z
1231 3213 4214
1231 3213 4214
rolnum=0
colnum=0

#閱讀txt到excel
def Txt_to_Excel(inputTxt, sheetName, start_row, start_col, outputExcel):
    ws = excel.get_sheet(sheetName)
    with open(inputTxt, "r") as file_txt:
        lines = file_txt. readlines() #不是很大的文件都可以先讀取出來
        # count = len(lines)
        rolnum =len(lines)
        rol=0
        #獲取每行數(shù)據(jù)
        for datasrol in lines:
            # print(datarol)
            # 列數(shù)歸0
            col=0
            datarol = datasrol. split(",")
            # print(datarol)
            row_excel = rol + start_row-1
            rol += 1
            #把數(shù)據(jù)按列插入
            for data in datarol:
                col_excel = col + start_col- 1
                # print(data)
                ws.write(row_excel, col_excel, data)
                excel.save (outputExcel)
                # print(col_excel)
                col +=1
    cotnum = col
    print("行數(shù), " + str(rolnum) + "列數(shù) " + str(colnum))
    return excel

#處理exceL,計算每列3組的平均值凳鬓,newSheet為空時代表輸入追加第一個sheet
def excelUnit(excelFile,newSheet,tabName):
    #結果輸入到新的sheet文件
    if newSheet != None and newSheet !='':
        #創(chuàng)建表格
        CreatExcel(sheetName=newSheet, tabName=tabName, outputExcel=excelFile)
        ws = excel.get_sheet (newSheet)
        col=0
        Data_0 = []
        i=0
        for data in tabName:
            col_excel = col + start_col -1
            df = pd.DataFrame (pd. read_excel(excelFile))
            print(data)
            while i < len(df):
                Data0 = df[data][i:i + group] # 每間隔3個數(shù)據(jù)取-次數(shù)
                print(Data0)
                Data1 = sum(Data0) / group # 求取每組數(shù)據(jù)的平均值
                Data_0. append((format(Data1,'.6f')))
                i=i+group
            print(Data_0)
            rol=0
            for data0 in Data_0:
                rol_excel = rol + start_row - 1
                ws. write(rol_excel, col_excel, data0)
                excel.save(excelFile)
                rol += 1
            col += 1
            Data_0 = []
            i=0
            return
        else:#追加到原來的sheet
            Data_0 = []
            i=0
            count=len(tabName)
            icount=0#用于合并增加列數(shù)
            for data in tabName:
                worksheet.excel.get_sheet(sheetname)
                worksheet.write(i,icount+count,data+'平均數(shù)')
                df = pd.DataFrame (pd. read_excel(excelFile))
                print(data)
                index=0
                while i < len(df):
                    Data0 = df[data][i:i + group] # 每間隔3個數(shù)據(jù)取-次數(shù)
                    print(Data0)
                    Data1 = sum(Data0) / group # 求取每組數(shù)據(jù)的平均值
                    Data_0.append((format(Data1,'.6f')))
                    #合并單元格
                    worksheet.write_merge(i+1,i+group , count+icount, count+icount, Data_0[int(index)], style=Style.default_style)
                    i=i+group

                    index+=1
                    #while index<group:
                        #index+=1
                        #Data_0.append('')
                print(Data_0)
                excel.save(excelFile)
                #df[data+"3組平均數(shù)"]=Data_0

                #df.to_excel(excelFile,sheetName,index=False)
                Data_0 = []
                i=0
                icount+=1
          return


# 創(chuàng)建excel, sheetName
def CreatExcel(sheetName, tabName, outputExcel):
    if sheetName == None and sheetName =='' :
        sheetName =" 默認sheet"
    ws = excel.add_sheet(sheetName)
    col=0
    for data in tabName:
        col_excel =col + start_col - 1
        ws.write(0, col_excel,data)
        excel. save (outputExcel)
        col+= 1
    return excel
#閱讀文件夾下的所有txt文件
def readTxtDir(path):
    findtxt = os.listdir(path) # 文件夾下的所有文件
    txtsPath=[]
    for file in findtxt:#遍歷文件夾
        if os.path.splitext(file)[1] == '.txt':
            # print(file)
            txtsPath.append(file)
    print(txtsPath)
    return txtsPath

if __name__ =='__main__'  :

    #原始文件參數(shù)
    outputExcel = '.xls' #輸入excel格式
    inputfileDir = 'D://yuanhua/test/case' # 文件目錄
    txts=readTxtDir(path=inputfileDir)
    for txt in txts:
        #創(chuàng)建文檔
        excel = xlwt .Workbook(encoding='utf-8')
        sheetName = "導航定位綜合誤差原始數(shù)據(jù)" # 需要寫入exceL中的Sheet中,可以自己
        tabName=['x','y','z']
        start_row = 2 # 從第2行開始寫
        start_col = 1 # 從第1列開始寫
        #轉換文件為excel
        outputExcel ='.xls'
        print(inputfileDir + "/" + txt)
        print(txt.split('.')[0] + outputExcel)
        outputExcel.txt.split('.')[0] + outputExcel
        inputfile = inputfileDir + "/" + txt
    
        excel = CreatExcel( sheetName=sheetName,tabName=tabName,outputExcel=outputExcel)
        Txt_to_Excel(inputTxt =inputfile, sheetName=sheetName, start_row=start_row,start_col=start_col,outputExcel=outputExcel)
    
        avgName = "平均值 "
        group = 3 # n個數(shù)據(jù)組合為一組
    
        # tabName = ['x', 'y', 'z']
    
        excelUnit(excelFile=outputExcel, newSheet=avgName, tabName=tabName)
    

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末患民,一起剝皮案震驚了整個濱河市缩举,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌匹颤,老刑警劉巖仅孩,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異印蓖,居然都是意外死亡辽慕,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門赦肃,熙熙樓的掌柜王于貴愁眉苦臉地迎上來溅蛉,“玉大人,你說我怎么就攤上這事他宛〈啵” “怎么了?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵厅各,是天一觀的道長镜撩。 經(jīng)常有香客問我,道長讯检,這世上最難降的妖魔是什么琐鲁? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮人灼,結果婚禮上围段,老公的妹妹穿的比我還像新娘。我一直安慰自己投放,他們只是感情好奈泪,可當我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著灸芳,像睡著了一般涝桅。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上烙样,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天冯遂,我揣著相機與錄音,去河邊找鬼谒获。 笑死蛤肌,一個胖子當著我的面吹牛壁却,可吹牛的內容都是我干的。 我是一名探鬼主播裸准,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼展东,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了炒俱?” 一聲冷哼從身側響起盐肃,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎权悟,沒想到半個月后砸王,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡僵芹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年处硬,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拇派。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡荷辕,死狀恐怖,靈堂內的尸體忽然破棺而出件豌,到底是詐尸還是另有隱情疮方,我是刑警寧澤,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布茧彤,位于F島的核電站骡显,受9級特大地震影響,放射性物質發(fā)生泄漏曾掂。R本人自食惡果不足惜惫谤,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望珠洗。 院中可真熱鬧溜歪,春花似錦、人聲如沸许蓖。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽膊爪。三九已至自阱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間米酬,已是汗流浹背沛豌。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留赃额,地道東北人加派。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓阁簸,卻偏偏與公主長得像,于是被迫代替她去往敵國和親哼丈。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內容