poythoncode-actual combat 5--excel file read, text file, csv file, save it in the system and store it in a large list

Read operation on excel


import os
import json
import 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=path
        self.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 e

    def read_json_file(self):
        """读取json文件"""
        try:
            with open(self.path,mode="r",encoding="utf-8") as fd:
                # 把json文件内容直接转为dict
                temp_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 e

    def read_excel_file(self,sheet:str,is_have_titel:bool):
        """读取excel文件"""
        try:
            # 实例化一个workbook对象
            workbook=openpyxl.load_workbook(self.path)
            # 指明是哪个sheet
            sheettab=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 e



def 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_list
        print(obj_student.student_list)
        print("split+++++")
        # 把每个小项的列表打印出来
        for item in obj_student.student_list:
            print(item)
        print("="*50)
        # 输出类似样式[{
    
    }{
    
    }...]样式的---->student_dict
        for 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()

Guess you like

Origin blog.csdn.net/wtt234/article/details/113630116