前几天接到一个任务,从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格式)...相关推荐

  1. python合并word表格单元格_Python实战009:读取Word文档中的表格数据及表格合并问题解决...

    同事最近被安排整理资料,主要工作室将文档中的表格数据提取出来并整理层Excel表格供我们FII刀具商城进行资料维护.由于刀具的种类繁多且规格无数,所以要处理的数据量相当的庞大.人工核对整理既费时又费力 ...

  2. Python3-word文档操作(五):利用python修改word文档中的表格数据

    1. 简介: 本篇继续学习python操作word文档的相关知识.本篇主要学习: 1)如何获取一个已经存在文档中的表格的内容: 2)如何修改一个已经存在文档中的表格的内容: 2. 获取word文档中的 ...

  3. python用字典统计单词出现次数_python - 如何使用字典理解来计算文档中每个单词的出现次数...

    我有一个用python编写的列表,其中充满了文本.就像每个文档中的固定单词.所以对于每个文档,我都有一个列表,然后在列表中列出所有文档. 所有列表只包含唯一的单词.我的目的是计算完整文档中每个单词的出 ...

  4. 用代码读取配置文档中的指定数据

    需求: 在XX游戏根目录中,读取其ini文档,找到游戏的主执行程序,然后运行. 比如我要读取罗马2全面战争的游戏根目录中的ini配置文档.读取到游戏的主程序是"Rome2",然后运 ...

  5. vue+docxtemplater实现读取word文档,根据后端数据生成echarts图表插入word,并下载为docx格式文件

    一.需求 word自带的图表不能满足需求,并且编写过程繁琐,需要写一个页面,主要功能是能读取服务器的word模板,根据后台给的数据,自动生成echarts图表并插入到word指定位置,然后点击能下载插 ...

  6. python svg2rlg_python提取pdf文档中的表格数据、svg格式转换为pdf

    提取pdf文件中的表格数据原文链接 https://www.analyticsvidhya.com/blog/2020/08/how-to-extract-tabular-data-from-pdf- ...

  7. python查数据库写入excel_【Python】将数据库中的数据查询出来自动写入excel文档...

    近期每天都要监控一个数据. 第一个版本是这样的: 每天新增一个文档来汇总这个数据.这样搞了几天之后,过了一个周末,过来突然发现数据变多了很多,这个时候要调整策略,直接一个文档汇总出要的数据就可以了. ...

  8. python将数据写入excel_【Python】将数据库中的数据查询出来自动写入excel文档

    近期每天都要监控一个数据.第一个版本是这样的: 每天新增一个文档来汇总这个数据.这样搞了几天之后,过了一个周末,过来突然发现数据变多了很多,这个时候要调整策略,直接一个文档汇总出要的数据就可以了. 这 ...

  9. Python:批量读取目录下jpg文件,并输出jpg文件的绝对路径到指定txt文档中。

    #功能:读取jpg文件,输出绝对目录到txt中. import os.path import glob import os"""https://blog.csdn.net ...

最新文章

  1. Python Excel 操作 | xlrd+xlwt 模块笔记
  2. linux rm 不释放_Linux解决rm 删除大文件后 磁盘空间无法释放的问题
  3. SpringBoot 整合Security——自定义表单登录
  4. 【原创】2009个性签名和流行语搜集
  5. Linux 图片传输功能c/c++(初版)
  6. linux网站目录在哪_果核建站教程【二】环境安装与搭建第一个网站
  7. python中isinstance(3、object)_python中isinstance函数判断各种类型的小细节
  8. Linux 两台服务器之间传输文件和文件夹
  9. ccie 与 java,上海ccie脚踏实地,java常量
  10. PAT (Basic Level) Practice1016 部分A+B
  11. 3.4 小乌龟git使用说明
  12. 学校计算机协会面试自我介绍,个人社团面试自我介绍范文三篇
  13. element-ui表格合并数据相同行
  14. 房价,经济转型,技术创新
  15. 2022年Q1手机银行用户规模达6.5亿,加强ESG个人金融产品创新
  16. Unity-遮挡剔除
  17. 公司章程违反了公司法该怎么办
  18. R语言主成分PCA、因子分析、聚类对地区经济研究分析重庆市经济指标
  19. L1、L2正则化总结
  20. PCIE设备的x1,x4,x8,x16有什么区别?

热门文章

  1. 解决:Unknown custom element: <myData> - did you register the component correctly? For recursive compon
  2. Java List<T>去重方法,引用类型集合去重
  3. js中比较时间字串大小
  4. C# 反射 (Reflect)
  5. oracle pl/sql 包
  6. 13,反转链表《剑指offer》
  7. Launcher结构之home screen
  8. 【转】英文论文中“such as, for example, e.g., i.e., etc., et al. ”的用法分析
  9. 大数据:互联网大规模数据挖掘与分布式处理
  10. Tomcat自定义部署