python逐行讀取txt寫入excel_用python從符合一定格式的txt文檔中逐行讀取數據并按一定規則寫入excel(openpyxl支持Excel 2007 .xlsx格式)...

前幾天接到一個任務,從gerrit上通過ssh命令獲取一些commit相關的數據到文本文檔中,隨后將這些數據存入Excel中。數據格式如下圖所示

242119152819994.png

觀察上圖可知,存在文本文檔中的數據符合一定的格式,通過python讀取、正則表達式處理并寫入Excel文檔將大大減少人工處理的工作量。

1. 從gerrit獲取原始信息,存入文本文檔:

$ssh –p 29418 @192.168.1.16 gerrit query status:merged since: 2>&1 | tee merged_patch_this_week.txt

2. 從txt文檔中讀取數據。

Python的標準庫中,文件對象提供了三個“讀”方法: .read()、.readline() 和 .readlines()。每種方法可以接受一個變量以限制每次讀取的數據量,但它們通常不使用變量。 .read() 每次讀取整個文件,它通常用于將文件內容放到一個字符串變量中。然而 .read() 生成文件內容最直接的字符串表示,但對于連續的面向行的處理,它卻是不必要的,并且如果文件大于可用內存,則不可能實現這種處理。

readline() 和 readlines()之間的差異是后者一次讀取整個文件,象 .read()一樣。.readlines()自動將文件內容分析成一個行的列表,該列表可以由 Python 的 for... in ... 結構進行處理。另一方面,.readline()每次只讀取一行,通常比 .readlines()慢得多。僅當沒有足夠內存可以一次讀取整個文件時,才應該使用.readline()。

patch_file_name="merged_patch_this_week.txt"patch_file=open(patch_file_name,'r') #打開文檔,逐行讀取數據

for line inopen(patch_file_name):

line=patch_file.readline()print line

3. 寫入到Excel文檔中

python處理Excel的函數庫中,xlrd、xlwt、xlutils比較常用,網上關于它們的資料也有很多。但由于它們都不支持Excel 2007以后的版本(.xlsx),所以只能忍痛放棄。

經過一番搜索,找到了openpyxl這個函數庫,它不僅支持Excel 2007,并且一直有人維護(當前最新版本為2.2.1,2015年3月31日發布)。官方的描述為:

A Python library to read/write Excel 2007 xlsx/xlsm files,它的文檔清晰易讀,相關網站:http://openpyxl.readthedocs.org/en/latest/index.html

安裝方法(windows 7):首先安裝jdcal模塊--解壓縮到某目錄,cd到該目錄,運行"python setup.py install"。 然后安裝openpyxl,方法相同。

寫入步驟如下:

1. 打開工作簿:

wb=load_workbook('Android_Patch_Review-Y2015.xlsx')

2. 獲得工作表

sheetnames =wb.get_sheet_names()

ws= wb.get_sheet_by_name(sheetnames[2])

3. 將txt文檔中的數據寫入并設置單元格格式

patch_file_name="merged_patch_this_week.txt"patch_file=open(patch_file_name,'r') #打開文檔,逐行讀取數據

ft=Font(name='Neo Sans Intel',size=11)for line inopen(patch_file_name):

line=patch_file.readline()

ws.cell(row=1,column=6).value=re.sub('project:','',line)#匹配project行,若匹配成功,則將字符串“project:”刪除,剩余部分寫入Excel第1行第6列

ws.cell(row=rows+1,column=1).font=ft

4. 保存工作簿

wb.save('Android_Patch_Review-Y2015.xlsx')

完整代碼如下:

from openpyxl.workbook importWorkbookfrom openpyxl.reader.excel importload_workbookfrom openpyxl.styles importPatternFill, Border, Side, Alignment, Protection, Fontimportre#from openpyxl.writer.excel import ExcelWriter#import xlrd

ft=Font(name='Neo Sans Intel',size=11) #define font style

bd=Border(left=Side(border_style='thin',color='00000000'),\

right=Side(border_style='thin',color='00000000'),\

top=Side(border_style='thin',color='00000000'),\

bottom=Side(border_style='thin',color='00000000')) #define border style

alg_cc=Alignment(horizontal='center',\

vertical='center',\

text_rotation=0,\

wrap_text=True,\

shrink_to_fit=True,\

indent=0) #define alignment styles

alg_cb=Alignment(horizontal='center',\

vertical='bottom',\

text_rotation=0,\

wrap_text=True,\

shrink_to_fit=True,\

indent=0)

alg_lc=Alignment(horizontal='left',\

vertical='center',\

text_rotation=0,\

wrap_text=True,\

shrink_to_fit=True,\

indent=0)

patch_file_name="merged_patch_this_week.txt"patch_file=open(patch_file_name,'r') #get data patch text

wb=load_workbook('Android_Patch_Review-Y2015.xlsx') #open excel to write

sheetnames =wb.get_sheet_names()

ws= wb.get_sheet_by_name(sheetnames[2]) #get sheet

rows=len(ws.rows)assert ws.cell(row=rows,column=1).value!=None, 'New Document or empty row at the end of the document? Please input at least one row!'

print "The original Excel document has %d rows totally." %(rows)

end_tag='type: stats'

for line inopen(patch_file_name):

line=patch_file.readline()if re.match(end_tag,line) is not None: #end string

break

if len(line)==1: #go to next patch

rows=rows+1

continueline=line.strip()#print line

ws.cell(row=rows+1,column=1).value=ws.cell(row=rows,column=1).value+1 #Write No.

ws.cell(row=rows+1,column=1).font=ft

ws.cell(row=rows+1,column=1).border=bd

ws.cell(row=rows+1,column=1).alignment=alg_cb

ws.cell(row=rows+1,column=5).border=bd

ws.cell(row=rows+1,column=9).border=bdif re.match('change',line) is notNone:

ws.cell(row=rows+1,column=2).value=re.sub('change','',line) #Write Gerrit ID

ws.cell(row=rows+1,column=2).font=ft

ws.cell(row=rows+1,column=2).border=bd

ws.cell(row=rows+1,column=2).alignment=alg_cbif re.match('url:',line) is notNone:

ws.cell(row=rows+1,column=3).value=re.sub('url:','',line) #Write Gerrit url

ws.cell(row=rows+1,column=3).font=ft

ws.cell(row=rows+1,column=3).border=bd

ws.cell(row=rows+1,column=3).alignment=alg_cbif re.match('project:',line) is notNone:

ws.cell(row=rows+1,column=6).value=re.sub('project:','',line) #Write project

ws.cell(row=rows+1,column=6).font=ft

ws.cell(row=rows+1,column=6).border=bd

ws.cell(row=rows+1,column=6).alignment=alg_lcif re.match('branch:',line) is notNone:

ws.cell(row=rows+1,column=7).value=re.sub('branch:','',line) #Write branch

ws.cell(row=rows+1,column=7).font=ft

ws.cell(row=rows+1,column=7).border=bd

ws.cell(row=rows+1,column=7).alignment=alg_ccif re.match('lastUpdated:',line) is notNone:

ws.cell(row=rows+1,column=8).value=re.sub('lastUpdated:|CST','',line) #Write update time

ws.cell(row=rows+1,column=8).font=ft

ws.cell(row=rows+1,column=8).border=bd

ws.cell(row=rows+1,column=8).alignment=alg_ccif re.match('commitMessage:',line) is notNone:

description_str=re.sub('commitMessage:','',line)if re.match('Product:|BugID:|Description:|Unit Test:|Change-Id:',line) is notNone:

description_str=description_str+'\n'+line # if re.match('Signed-off-by:',line) is notNone:

description_str=description_str+'\n'+line

ws.cell(row=rows+1,column=4).value=description_str #Write patch description

ws.cell(row=rows+1,column=4).font=ft

ws.cell(row=rows+1,column=4).border=bd

ws.cell(row=rows+1,column=4).alignment=alg_lc

wb.save('Android_Patch_Review-Y2015.xlsx')print 'Android_Patch_Review-Y2015.xlsx saved!\nPatch Collection Done!'

#patch_file.close()

目前為止,基本功能已經實現,但是還有兩個問題沒有搞明白:

第一個是完整代碼中的最后一句注釋行,我搜到的幾篇介紹openpyxl的博客中,打開文件后都沒有close,所以我在代碼中也沒有close。理論上感覺還是需要的。等對文件對象的理解更加深入一些時會繼續考慮這個問題。

第二是運行該腳本時有一個warning," UserWarning: Discarded range with reserved name,warnings.warn("Discarded range with reserved name")“,目前還在搜索原因,如有明白的,也請不吝告知。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/457797.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/457797.shtml
英文地址,請注明出處:http://en.pswp.cn/news/457797.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

筋斗云newcloud錯誤碼列表

響應碼信息備注440Ip Error客戶送IP錯誤441Callee Number Error被叫號碼位數錯誤(標準11位正確,錯誤加前綴0,或其他前綴)442Called Operator Error被叫運營商錯誤(支持移動,不支持聯通電信)443N…

Extjs 之 initComponent 和 constructor的區別(轉)

在創建自定義類時,先構造(constructor)后初始化(initComponent)。如:(在舊的Extjs 版本中使用 Ext.extend 實現擴展) Ext.define(Btn,{ extend:Ext.button.Button, init…

hive遍歷_從Hive中的stored as file_foramt看hive調優

一、行式數據庫和列式數據庫的對比1、存儲比較行式數據庫存儲在hdfs上式按行進行存儲的,一個block存儲一或多行數據。而列式數據庫在hdfs上則是按照列進行存儲,一個block可能有一列或多列數據。2、壓縮比較對于行式數據庫,必然按行壓縮&#…

oracle sql語句 從指定條數查詢

現有表A 查詢從第10行之后的數據 select a from ( select a, rownum r from A ) where r > 10 order by r; 實際工作中例子 select account,acct_name from ( select account, acct_name, rownum r from pmctl_nonsleep_acct ) where r > 10 order by

幫助孩子學會感恩_頁數204_出版日期2015.03_完整版PDF電子書下載

幫助孩子學會感恩_頁數204_出版日期2015.03_完整版PDF電子書下載 帶索引書簽目錄高清版_13813212 下載鏈接http://pan.baidu.com/s/1geEmUeZ 【作 者】(英)蒂姆惠特尼(TimWhitney)著【叢書名】陪孩子成長系列叢書【形態項】 204 …

xwpftablecell設置字體樣式_HTML的文字樣式

font 屬性可以用來作為 font-style, font-variant, font-weight, font-size, line-height 和 font-family 屬性的簡寫,或將元素的字體設置為系統字體。字體修改font-family 屬性:設置HTML頁面中的字體font-size 屬性:設置字體大小font-weight…

將中文標點符號替換成英文標點符號

/// 轉全角的函數(SBC case) /// ///任意字符串 /// 全角字符串 /// ///全角空格為12288,半角空格為32 ///其他字符半角(33-126)與全角(65281-65374)的對應關系是:均相差65248 ///public string ToSBC(string input) { //半角轉全角:char[] cinput.ToCh…

Centos6.5升級GCC

由于CentOS自帶的gcc實在是老掉牙了,所以決定升級一下gcc,下面介紹如何進行源碼編譯,升級gcc。 從GNU網站下載你想要的gcc版本,鏈接:ftp://ftp.gnu.org/gnu/gcc/,選擇合適的gcc版本,然后下載&am…

oracle sql語句 exists

exists 這個關鍵字只是個查詢條件 用來判斷后面跟的查詢語句是否查找到記錄 查找到為真 反之為假 例子 select * from ammst_corp a where account 999999999999999999 and exists ( select 1 from pmrgt_unit where unit_code a.open_unit ) 查找 9999999999999999…

python金字塔_高斯金字塔與拉普拉斯金字塔的原理與python構建

高斯金字塔和拉普拉斯金字塔【1】在圖像相關領域應用廣泛,尤其是圖像融合和圖像分割方面。本文從理論和opencv實現兩個方面對兩種金字塔進行了介紹,并給出了二者的視覺效果。1、高斯金字塔在計算機視覺與圖像處理相關任務中,經常需要使用同一…

mongodb在32位機的連接

Windows 32bit版本安裝Mongodb時,會發生的下面問題 2016-05-09T00:09:45.1240800 I STORAGE [initandlisten] exception in initAndListen: 28663 Cannot start server. The default storage engine wiredTiger is not available with this build of mongod. Pleas…

oracle sql 語句 start with ...... connect by prior .......

這個查詢條件可以理解為遞歸查詢 select up_unit_code from pmctl_nuit START WITH unit_code 1188899Q CONNECT BY PRIOR up_unit_code unit_code 語句理解: 首先根據條件 START WITH unit_code 查詢到 up_unit_code 顯示 然后 CONNECT BY P…

cnetos7安裝zabbix3.0.3安裝手冊

親測可用呀。學習好幾天 最好用的文檔詳見附件http://down.51cto.com/data/2251232轉載于:https://blog.51cto.com/11802086/1863554

python文件夾目錄_Python 操作文件、文件夾、目錄大全

#-*- coding: utf-8 -*-importosimportshutil#一. 路徑操作:判斷、獲取和刪除#1. 得到當前工作目錄,即當前Python腳本工作的目錄路徑: os.getcwd()#print: currentpath: f:\LearnPythoncurrentpath os.getcwd()print "currentpath:",currentpa…

LightOJ 1370 Bi-shoe and Phi-shoe(歐拉函數)

題意:題目給出一個歐拉函數值F(X),讓我們求>這個函數值的最小數N,使得F(N) > F(X); 分析:這個題目有兩種做法。第一種,暴力打出歐拉函數表,然后將它調整…

15-CSS基礎-浮動流

浮動 網頁的布局方式 什么是網頁的布局方式? 網頁的布局方式其實就是指瀏覽器是如何對網頁中的元素進行排版的 標準流(文檔流/普通流)排版方式 其實瀏覽器默認的排版方式就是標準流的排版方式在CSS中將元素分為三類, 分別是塊級元素/行內元素/行內塊級元素在標準流中有兩種排版…

oracle sql 排序

當有多個排序列時 并且每列都是降序排序 需要在每個列名后 寫desc

遷移DirectX11到VS2015 Win10

書本中的例子遷移:Introduction to 3D Game Programming with Direct3D 11.0 顏色:DirectXColors.h and the DirectX::Colors namespace. 效果:Effect framework編譯后只需兩個文件,d3dx11effect.h及生成的lib文件。 紋理&#xf…

python監控網頁更新_python監控網頁更新

{"moduleinfo":{"card_count":[{"count_phone":1,"count":1}],"search_count":[{"count_phone":4,"count":4}]},"card":[{"des":"阿里技術人對外發布原創技術內容的最大平臺&…

git-- 使用

git 使用時兩個人沖突: Resolve conflicts