poythoncode-actual combat 4--read text files, csv files, save them in the system and store them in a large list

1. Procedure interpretation


import os

"""
程序作用读取UTF8格式的记事本或者csv文件--->存储在在系统中,两种方式的存储
1.存储成为外面是列表,列表里面多个小列表[[],[],....]
2.存储成为外面是列表,列表里面多个小字典[{
    
    },{
    
    },....]
3.通过main函数调取相应内容进行测试.....
"""

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



if __name__ == '__main__':
    # 准备一个文件路径
    path=os.path.join('table综合','New6108.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)
    except Exception as e:
        print("读取文件出现异常,具体原因"+str(e))

Guess you like

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