日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python逐行读取txt写入excel_用python从符合一定格式的txt文档中逐行读取数据并按一定规则写入excel(openpyxl支持Excel 2007 .xlsx格式)...

發布時間:2023/12/20 python 28 豆豆

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

觀察上圖可知,存在文本文檔中的數據符合一定的格式,通過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")“,目前還在搜索原因,如有明白的,也請不吝告知。

總結

以上是生活随笔為你收集整理的python逐行读取txt写入excel_用python从符合一定格式的txt文档中逐行读取数据并按一定规则写入excel(openpyxl支持Excel 2007 .xlsx格式)...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。