纯文本文件 numbers.txt, 里面的内容(包括方括号)如下所示:
[
[1, 82, 65535],
[20, 90, 13],
[26, 809, 1024]
]
用json处理文件
# -*- coding:utf-8 -*- import xlwt,json with open('number.txt','r')as file_open: data=json.load(file_open) workbook=xlwt.Workbook() sheet=workbook.add_sheet('number') for x,list1 in enumerate(data): for y,value in enumerate(list1): sheet.write(x,y,value) workbook.save('numberjson.xls')
用正则表达式处理:
# -*- coding:utf-8 -*- import xlwt,re workbook=xlwt.Workbook(encoding='utf-8') sheet=workbook.add_sheet('number',cell_overwrite_ok=True) info=re.compile(r'\[(\d+), (\d+), (\d+)\]')#注意把空格也加上 def horz_rightstyle():#加了一些样式 algnt=xlwt.Alignment()#对齐属性对象 algnt.horz=xlwt.Alignment.HORZ_RIGHT#右对齐 style=xlwt.XFStyle() style.alignment=algnt return style
with open('number.txt') as file_open:
data=file_open.read()
l=info.findall(data)
print l
for x,list1 in enumerate(info.findall(data)):
print x,list1
for y,value in enumerate(list1):
sheet.write(x,y,value,horz_rightstyle())#加右对齐样式
workbook.save('number.xls')