#将某txt的内容写入到xls文件中 #打开源文件目录,读取文件,解析成json格式,再按要求写入xls中 import json import xlwt from collections import OrderedDict def run_1(): with open ('student.txt','r') as f:#打开文件 content = f.read()#读取文件 #loads()方法把str对象反序列化为json对象,自定义解码器为ordereddict #转化为json,因为转化后的dict的元素位置和转化前有可能不一样,因此要使用orfereddict d = json.loads(content,object_pairs_hook = OrderedDict) #print(d) file = xlwt.Workbook()#初始化xls文件 table = file.add_sheet('test')#添加sheet工作表,名字为test for row,i in enumerate(d):#读取所有字典,row为序号,i为字典关键字key table.write(row,0,i)#写入行号,列号,key for col,j in enumerate(d[i]):#col为序号,j为value,有多个,需要迭代 table.write(row,col+1,j) file.save('student.xls') def run_2(): with open('city.txt', 'r') as f: content = f.read() d = json.loads(content,object_pairs_hook = OrderedDict) #print(d) file = xlwt.Workbook() table = file.add_sheet('test') for row, i in enumerate(d): table.write(row, 0, i) table.write(row, 1, d[i]) file.save('city.xls') def run_3(): with open('number.txt', 'r') as f: content = f.read() d = json.loads(content, object_pairs_hook = OrderedDict) #print(d) file = xlwt.Workbook() table = file.add_sheet('test') for row, i in enumerate(d): for col, j in enumerate(i): table.write(row, col, j) file.save('number.xls') if __name__ == '__main__': run_1() run_2() run_3()
Python每日练习 14 15 16 将某txt的内容写入到xls文件中
最新推荐文章于 2021-04-28 20:55:31 发布