1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > poythoncode-实战5--excel 文件读取 文本文件 csv文件 存到系统中以大列表方式进行存储

poythoncode-实战5--excel 文件读取 文本文件 csv文件 存到系统中以大列表方式进行存储

时间:2018-08-16 10:16:36

相关推荐

poythoncode-实战5--excel 文件读取 文本文件 csv文件 存到系统中以大列表方式进行存储

对excel读取操作

import osimport jsonimport openpyxl"""程序作用读取UTF8格式的记事本或者csv文件--->存储在在系统中,两种方式的存储1.存储成为外面是列表,列表里面多个小列表[[],[],....]2.存储成为外面是列表,列表里面多个小字典[{},{},....]3.通过main函数调取相应内容进行测试.....==========================读取文件使用open函数,有三个方法:1.read()。。。把整个文件一次读取到str中2.readlines()。。。把整个文件一次读取到list集合,一行是一个元素3.readline()。。。一次读取一行,处理完后,读取下一行""""""采用readline读取文件方式:第一步:先读取一行第二步:判断如果这一行如果有数据进行的操作第三步:在循环的最后再读取一行,进行判断第四步:只到获取数据的行,没有数据了,就是跳出循环one_line=fd.readline()# 判断这一行是否有数据while one_line:# 处理数据one_line_list=one_line.strip().split(",")................#读取下一行,这地方是精髓地方....one_line = fd.readline()"""class Student:"""1.path:str 为项目文件的路径2.infos:list 这个是字典key值"""def __init__(self,path:str,infos:list):# 把pyth 定义文件的路径self.path=pathself.infos=infos# 读取文件后期存储的格式如下 [[],[]...]或者[{},{}...]这两种样式self.student_list=[]self.student_dict=[]def read_txt_file(self):"""读取文本文件、csv文件"""# 使用异常处理结构try:with open(self.path,"r",encoding="utf8") as fd:# with open(self.path,"r") as fd:# 读取第一行数据,先读取一行看看有没有数据,然后处理数据one_line=fd.readline()# 判断这一行是否有数据while one_line:# 处理数据one_line_list=one_line.strip().split(",")# 1.存储为[[],[]...]格式类型self.student_list.append(one_line_list)# 2.存储为[{},{}...]格式类型# 2.1定义一个临时的字典集合# 2.2 遍历temp_dict={}for index,value in enumerate(self.infos):# 把key ,value 拼接成字典# 从一个输入“infos”列表中,获取未来字典的key,同时获取列表中的值进行绑定成新的字典temp_dict[value]=one_line_list[index] # 重要!!!# 2.3 附加到list中self.student_dict.append(temp_dict)#读取下一行,这地方是精髓地方....one_line = fd.readline()except Exception as e:raise edef read_json_file(self):"""读取json文件"""try:with open(self.path,mode="r",encoding="utf-8") as fd:# 把json文件内容直接转为dicttemp_dict=json.load(fp=fd)# print(temp_dict)# print(type(temp_dict))# 1.读取的信息转为list格式,---使用循环逐行读取for studentdict in temp_dict['RECORDS']:# print(studentdict)# 取一条字典中的values值,形成列表one_list1=studentdict.values()# print(one_list1)self.student_list.append(list(one_list1))# 2.读取的信息转为字典格式,---使用循环逐行读取# 本省就是字典结构了,直接遍历存放在student_dict中,就可以了except Exception as e:raise edef read_excel_file(self,sheet:str,is_have_titel:bool):"""读取excel文件"""try:# 实例化一个workbook对象workbook=openpyxl.load_workbook(self.path)# 指明是哪个sheetsheettab=workbook[sheet]# 开始遍历 ====>list(list())for index,row in enumerate(sheettab.rows):# 定义一个学生list格式,dict格式one_student_list=[]one_student_dict={}# 判断是否有表头[excel表头]if index==0:if is_have_titel: # 如果有表头,跳过这一行continue# 遍历每一行数据for row_index,row_value in enumerate(row):one_student_list.append(row_value.value)# 准备one_student_dict数据one_student_dict[self.infos[row_index]]=row_value.value#附件到总的list中self.student_list.append(one_student_list)self.student_dict.append(one_student_dict)except Exception as e:raise edef calltextcsvfile():# 准备一个文件路径# path=os.path.join('table综合','New6108.csv')# path="E:/htcode/htlabpython3/pmfinishi/table/New61081.csv"# 实例化一个对象# infos 字段信息是后续的字典里面的key的提供者,但是列表中不适用!infos=['ID','name','flag','state']obj_student=Student(path,infos)try:# 输出obj_student.read_txt_file()# 输出类似[[],[]...]样式的列表内容--->student_listprint(obj_student.student_list)print("split+++++")# 把每个小项的列表打印出来for item in obj_student.student_list:print(item)print("="*50)# 输出类似样式[{},{}...]样式的---->student_dictfor itemdict in obj_student.student_dict:print(itemdict)print("=" * 50)except Exception as e:print("读取文件出现异常,具体原因"+str(e))def calljsonfile():# pathjson = "E:/htcode/htlabpython3/pmfinishi/table/table综合/gblablimit.json"pathjson = "E:/htcode/htlabpython3/pmfinishi/table/table综合/gblab.json"infos = ['ID', 'name', 'flag', 'state']obj_student = Student(pathjson, infos)obj_student.read_json_file()print(obj_student.student_list)for listitem in obj_student.student_list:print(listitem)# print(obj_student.student_list)# print("+"*100)# for item in obj_student.student_list:#print(item)def callexcelfile():path="E:/htcode/htlabpython3/pmfinishi/table/table综合/stu.xlsx"infors=["姓名","电话","地址","性别","爱好1","爱好2"]obj_studentexcel=Student(path,infors)sheet1=obj_studentexcel.read_excel_file("学生信息表",True)print(obj_studentexcel.student_list)for listitem in obj_studentexcel.student_list:print(listitem)print("*"*20)print(obj_studentexcel.student_dict)# for ditkey,ditvalue in obj_studentexcel.student_dict.items():#print(ditkey,ditvalue)if __name__ == '__main__':# calltextcsvfile()# calljsonfile()callexcelfile()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。