.propertise文件通常用来存储属性资源,文件内容主要包括注释、键值对,如[key]=[value]。
本篇用python实现将.propertise文件转换成excel文件,支持对单个.propertise和对某个目录下所有.propertise文件的解析。
用到的第三方包为xlwt,支持操作excel,包括新建excel文件,添加表单,保存操作。
源码如下:
1 #!/usr/local/bin/python 2 # -*- coding: utf-8 -*- 3 4 5 ######################################################################## 6 7 #功能:将propertise文件转换成excel,支持传文件夹和文件的绝对路径, 8 # 输入文件夹路径将转换文件夹内所有.properties文件到一个excel文件。 9 #Author:RaySon101 10 11 ######################################################################## 12 13 import os 14 import xlwt 15 16 #解析propertise 文件,追加到excel中 17 def propertise_to_excel(fileName,path): 18 global ws 19 global row 20 21 #校验文件后缀 22 if(os.path.splitext(path)[1] != '.properties'): 23 return 24 file = open(path,'r') 25 26 while 1: 27 lines = file.readlines(10000) 28 if not lines: 29 break 30 for line in lines: 31 line = line.decode("utf-8").strip() 32 if(line == ''): 33 continue 34 #print "line --- " + line.decode("utf-8") 35 strs = line.split('=',1) 36 if(len(strs) != 2): 37 continue 38 ws.write(row, 0, fileName) 39 ws.write(row, 1, strs[0].strip()) 40 ws.write(row, 2, strs[1].strip()) 41 row+=1 42 43 #递归遍历path下及其所有层级子目录下的文件 44 def transfer_all_propertise(path): 45 if not os.path.isdir(path): 46 propertise_to_excel(path.split("\\")[-1],path) 47 else: 48 files = os.listdir(path) 49 for file in files: 50 if os.path.isdir(path+'\\'+file): 51 transfer_all_propertise(path+'\\'+file) 52 else: 53 propertise_to_excel(file,path+'\\'+file) 54 55 56 if __name__ == '__main__': 57 #获得文件目录/文件 58 while(1): 59 root_path = raw_input("please input path [input 'Q/q' to exit] : ") 60 if(root_path == 'Q' or root_path == 'q'): 61 exit() 62 fileName = root_path.split('\\')[-1] 63 print fileName 64 wb = xlwt.Workbook() 65 ws = wb.add_sheet(fileName,'utf-8') 66 row = 2 67 transfer_all_propertise(root_path) 68 wb.save(fileName+'.xlsx')
由于是工作中临时用来紧急处理一项任务,这个工具仅仅针对当时具体需求的简单场景,没有做过多的容错处理和校验,有时间再优化几点:
1,兼容处理多种键值对的方式,包括key:value,key value.
2,容错处理,针对非法输入的过滤
3,支持读取已存在的excel文件,并追加新表单
欢迎指正
浙公网安备 33010602011771号