Python實現TXT、CSV、XLS等格式轉換 and 圖像顯示(超詳細教程)

數據處理整理

處理點雲數據的心得
使用xlwt對xls進行寫操作
使用xlrd對xls進行讀操作,可以直接讀出文件的行數和列數
使用pandas也可以對csv、xls文件進行讀寫、兩種格式轉換,將兩個文件進行合併在一起,將多個sheet列表整合在一個文件中
NOTE: csv類似於txt格式,針對csv格式,有專門的csv模塊處理

程序如下:

from __future__ import division
import shutil
import pandas as pd     #Pandas使用一個二維的數據結構DataFrame來表示表格式的數據,相比較於Numpy,Pandas可以存儲混合的數據結構,同時使用NaN來表示缺失的數據
import matplotlib     #繪製曲線圖
import matplotlib.pyplot as plt
import xlrd        #用於處理excel文件
import xlwt
from xlrd import open_workbook
import matplotlib as mpl
import os    #用於處理文件
import sys      #系統操作,帶上就行了
import csv
##腳本81,84,89可用於修改txt文檔的隔開形式(' ' , ',' , '\t')

filedir = os.path.dirname(sys.argv[0])      #獲取腳本所在目錄
os.chdir(filedir)       #將腳本所在的目錄設置爲工作目錄
wdir = os.getcwd()        #返回當前目錄
print('當前工作目錄:{}\n'.format(wdir))      #打印當前工作目錄

1 rename

for parent, dirs, files in os.walk(wdir):
    i = 1
    parent_base = os.path.basename(parent)  # 返回path最後的文件名
    if 'data' in parent_base:     #判斷data文件夾是否存在
        os.chdir('data')      #將data文件夾設置爲當前目錄
        for file in files:
            # file_ext = file.split('.')[-1]         #返回文件的路徑和文件名
            file_qian = file.split('.')[-2]    #對文件進行rename
            tmp = parent.split('\\')
            # new_name = 'data' + '/' + 'obj' + '/' + str(i).zfill(8) + '.' + file_ext
            new_name = file_qian + '.' + 'txt'

            old_path = os.path.join(parent, file)  # 分離的部分合成一個整體
            new_path = os.path.join(parent, new_name)
            os.rename(old_path, new_path)    
            i += 1    
print('已完成 abc -- > txt 格式轉化')    
filedir = os.path.dirname(sys.argv[0])      #獲取腳本所在目錄
os.chdir(filedir)       #將腳本所在的目錄設置爲工作目錄
wdir = os.getcwd()        #返回當前目錄
print('當前工作目錄:{}\n'.format(wdir))      #打印當前工作目錄 

for parent, dirs, files in os.walk(wdir):    #遍歷腳本目錄所有文件
    i = 0
    parent_base = os.path.basename(parent)  # 返回path最後的文件名
    if 'data' in parent_base:
        print(parent)
        os.chdir(parent)
        #os.chdir('data')
        os.mkdir('results')
        w = 0
        list = []
        writer = pd.ExcelWriter('many_sheets.xls')    #保存結果到已存在的excel文檔中

        for file in files:
            old_front = file.split('.')[0]     #對文件進行重命名
            old_ext = file.split('.')[-1]
            old_name = old_front + '.' + old_ext
            hour = old_front.split('-')[-1]
            print('小時', hour)
            new_name = old_front + '.' + 'xls'

2 open(data.txt)

		   #if file.split('.')[-1] == "txt":
           #   new_name = file.split('.')[0] + '.' + 'xls'
           #     df = open(file, 'r')
           #    lines = df.readlines()
           #     for line in lines:
           #         if line.strip() == '':
           #             continue
           #          if line.strip() == '"':
           #             continue
		                 
            open_txt  = open(file,'r',encoding='utf-8')   #打開txt文檔
            next(open_txt)   

3 xls(寫入)

            workbook = xlwt.Workbook()   #初始化xlwt
            sheet_1 = workbook.add_sheet(old_front,cell_overwrite_ok = True)    #對打開excel文檔進行添加sheet_1 

            q =0
            for line in open_txt:   #txt文檔的每一行都進行執行
                line = open_txt.readline()   #閱讀每一行的內容
                if line.strip() == '':    #line.strip()是移除字符串頭尾指定的字符(默認爲空格或換行符)或字符序列
                    continue
                if line.strip() == '"':
                    continue    
                for h in range(len(line.split(' '))):     #對特定的某行進行處理
                    if h == 0:
                        first_cell = line.split(' ')[0]
                        minute = first_cell.split(':')[0]
                        second = first_cell.split(':')[-1]
                        item = hour + ':' + minute + ':' +  second
                    else:
                        item = line.split(' ')[h]

                    sheet_1.write(q,h,item)  #定義的excel的shee_1中寫入數據
                q = q + 1    
            workbook.save(new_name)   #對寫入數據的sheet_1的excel進行保存
            data_collect = pd.read_excel(new_name,index_col = 0,header = None)   #使用pd打開文檔
            data_collect.to_excel(writer,sheet_name = hour,header = False)   #一個excel同時保存多個sheet文檔
            writer.save()  #對保存有多個sheet的excel進行保存
            
            list.append(q)
            print(list)

4 shutil() 複製和剪切

            shutil.copy(new_name,'results')   #將文件複製到“result”,前面是文件,後面是目錄
        shutil.move('many_sheets.xls', 'results')  #move相當於剪切,remove相當於刪除
        sum = 0
        for p in range(len(list)):
            sum = sum + list[p]
        print('all_總行數爲:',sum)

print('已將將所有的數據轉化爲xls格式文件!')

print('list0',list[0])
filedir = os.path.dirname(sys.argv[0])      #獲取腳本所在目錄
os.chdir(filedir)       #將腳本所在的目錄設置爲工作目錄
wdir = os.getcwd()        #返回當前目錄
print('當前工作目錄:{}\n'.format(wdir))      #打印當前工作目錄

for parent, dirs, files in os.walk(wdir):
    i = 0
    parent_base = os.path.basename(parent)  #返回path最後的文件名
    print(parent_base)
    if 'results' in parent_base:
        print(parent)
        os.chdir(parent)
        u = 0
        x = 0
        sum_c = 0
        i = 0
        m = 0

5 pd閱讀 .xls特定單元格

        workbook = xlwt.Workbook()     #將xlwt進行初始化
        sheet2 = workbook.add_sheet('all', cell_overwrite_ok=True)   #添加文檔sheet2
        # workbook = xlwt.Workbook()
        # sheet3 = workbook.add_sheet('diagram', cell_overwrite_ok=True)
        for file in files :
            df = pd.read_excel(file,header=0,index_col=None)  #使用pd閱讀文檔
            if i > (len(list) - 1):
                break
            long = list[i]
            print(long)

            for x in range(long-1) :
                for y in range(12) :
                    item = df.ix[x,y]   #閱讀excel文件的特定的單元格
                    # print(item)
                    sheet2.write(m,y,str(item))    #將excel文件寫入到同一個sheet2,這種寫法不實用,可以使用矩陣代替
                m = m + 1
            i = i + 1
            workbook.save('all_data.xls')  #將多個sheet保存在同一個sheet中

6 多個sheet保存在同一個 .xls中

        data_collect = pd.read_excel('all_data.xls', index_col=0, header=None)  #使用pd打開excel文檔
        data_collect.to_excel(writer, sheet_name='all_date', header=False)   #將多個sheet保存在同一個excel文檔中
        writer.save()   #對文檔進行保存
        print('all_data.xls 已經成功!')

        ax = 0
        ay = 0
        d = -1

7 pd閱讀xls特定文本框、xlwt寫入

        workbook = xlwt.Workbook()   #對xlwt進行初始化
        sheet3 = workbook.add_sheet('diagram', cell_overwrite_ok=True)  #創建sheet3

        nm = pd.read_excel('all_data.xls',header=0,index_col=None)   #使用pd閱讀文檔
        for ax in range(200):
            if ax % 25 == 0:
                d = d + 1
                for ay in range(11):
                    cell = nm.ix[ax,ay]  #閱讀特定單元格的內容
                    sheet3.write(d,ay,str(cell))   #將閱讀的內容寫入到sheet3中

        workbook.save('diagram.xls')  

        data_collect_2 = pd.read_excel('diagram.xls', index_col=0, header=None)
        data_collect_2.to_excel(writer, sheet_name='diagram', header=False)   #將多個sheet保存在同一個excel中
        writer.save()
        print('diagram.xls 已經成功!')

8 pd將xls轉化爲csv格式

        data_xls = pd.read_excel('diagram.xls',index_col=0)  #使用pd閱讀excel文件
        data_xls.to_csv('diagram1.csv')    #使用pd將excel文件保存成csv

9 創建csv並寫入

        with open('diagram.csv', 'w', newline="") as csvfile:  # 打開header-1.csv,沒有就創建一個,newline是保證寫入之後不自動空格
            writer_2 = csv.writer(csvfile)  # 對文件進行寫操作

            # 先寫入columns_name
            writer_2.writerow(["time", "V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12", "V13", "V14"])
        with open('diagram.csv','ab+') as f :
            f.write(open('diagram1.csv','rb').read())  #對csv進行寫操作

        df = pd.read_csv('diagram.csv')   #閱讀csv文件

10 matplotlib 顯示圖像

#使用matplotlib進行顯示csv文檔
        figsize = 12, 12  # 圖表的大小
        plt.subplot(331)  # subplot(221)創建2*2的圖表1表示在第一個
        plt.plot(df['time'], df['V1'])  # plot(a,b)進行繪製曲線,a表示橫座標,b表示縱座標,df['time']表示索引第一行爲time的那一列
        plt.xticks(rotation=90)  # 創建的matplotlib表格旋轉45°
        plt.ylabel(u'電池板電壓(V)', fontproperties='SimHei')  # y軸的標籤
        plt.xlabel(u'時間', fontproperties='SimHei')  # y軸的標籤

        plt.subplot(332)
        plt.plot(df['time'], df['V2'])
        plt.xticks(rotation=90)
        plt.ylabel(u'電池板電流(A)', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')

        plt.subplot(333)
        plt.plot(df['time'], df['V3'])
        plt.xticks(rotation=90)
        plt.ylabel(u'蓄電池電壓(V)', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')
		
        plt.subplot(334)
        plt.plot(df['time'], df['V4'])
        plt.xticks(rotation=90)
        plt.ylabel(u'蓄電池電流(A)', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')
		
        plt.subplot(335)
        plt.plot(df['time'], df['V5'])
        plt.xticks(rotation=90)
        plt.ylabel(u'環境溫度(℃)', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')

        plt.subplot(336)
        plt.plot(df['time'], df['V7'], 'b', label=u"充電功率(W)")
        plt.plot(df['time'], df['V8'], 'k', label=u"發電功率(W)")
        plt.xticks(rotation=90)
        plt.ylabel(u'充電/發電功率', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')
		
        plt.subplot(337)
        plt.plot(df['time'], df['V10'], 'b', label=u"累計充電(Ah)")
        plt.plot(df['time'], df['V11'], 'k', label=u"累計放電(Ah)")
        plt.xticks(rotation=90)
        plt.ylabel(u'累計充電/放電', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')

        # myfont = matplotlib.font_manager.FontProperties(fname='C:/Windows/Fonts/msyh.ttf')   #處理matplotlib中中文顯示的問題
        # mpl.rcParams['axes.unicode_minus'] = False
        # plt.grid(True)  #顯示網格線
        plt.show()

        plt.plot(df['time'], df['V1'])  # plot(a,b)進行繪製曲線,a表示橫座標,b表示縱座標,df['time']表示索引第一行爲time的那一列
        plt.xticks(rotation=90)  # 創建的matplotlib表格旋轉45°
        plt.ylabel(u'電池板電壓(V)', fontproperties='SimHei')  # y軸的標籤
        plt.xlabel(u'時間', fontproperties='SimHei')  # y軸的標籤
        plt.show()

        plt.plot(df['time'], df['V2'])
        plt.xticks(rotation=90)
        plt.ylabel(u'電池板電流(A)', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')
        plt.show()

        plt.plot(df['time'], df['V3'])
        plt.xticks(rotation=90)
        plt.ylabel(u'蓄電池電壓(V)', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')
        plt.show()

        plt.plot(df['time'], df['V4'])
        plt.xticks(rotation=90)
        plt.ylabel(u'蓄電池電流(A)', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')		

        plt.plot(df['time'], df['V5'])
        plt.xticks(rotation=90)
        plt.xlabel(u'時間', fontproperties='SimHei')
        plt.ylabel(u'溫度(℃)', fontproperties='SimHei')
        plt.show()

        plt.plot(df['time'], df['V7'], 'b', label=u"充電功率(W)")
        plt.plot(df['time'], df['V8'], 'k', label=u"發電功率(W)")
        plt.xticks(rotation=90)
        plt.ylabel(u'充電/發電功率', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')
        plt.show()
		
        plt.plot(df['time'], df['V10'], 'b', label=u"累計充電(Ah)")
        plt.plot(df['time'], df['V11'], 'k', label=u"累計放電(Ah)")
        plt.xticks(rotation=90)
        plt.ylabel(u'累計充電/放電', fontproperties='SimHei')
        plt.xlabel(u'時間', fontproperties='SimHei')
       print('over!')

	
       # # show data
# plt.scatter(x, y, c='magenta', s=50, alpha=0.5, label='train')
# plt.scatter(test_x, test_y, c='cyan', s=50, alpha=0.5, label='test')
# plt.legend(loc='upper left')
# plt.ylim((-2.5, 2.5))
# plt.show()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章