python_文件读取

"""读取txt文本中得数据。数据格式:name:password"""
    def read_txt(self,filepath,filename):
        """with open 使用时节省掉异常操作和关闭文件流写法,已包装好的内置函数"""
         with(open(filepath+"/"+filename,'r')) as user_file:
            self.data = user_file.readlines()

            users = []
            for line in self.data:
                print (chardet.detect(line)['encoding'])
                user= line.decode("utf-8")[:-1].split(":")
                users.append(user)
            return users


    def read_csv(self,filepath,filename):
        """读取excel文件中得数据"""
        # 用codecs提供的open方法来指定打开的文件的语言编码
        data = csv.reader(codecs.open(filepath+"/"+filename,'r'))
        users = []
        for line in islice(data,1,None):
            """islice去除第一行"""
            users.append(line)

        return users



    def read_excel(self,filepath,filename):
        """读取excel文件"""
        book = xlrd.open_workbook(filepath+"/"+filename)
        sheet = book.sheets()[0]
        nrows = sheet.nrows
        users = []
        for line in range(nrows):
            if line==0:
                continue
            users.append(sheet.row_values(line))
        return users


    def read_json(self,filepath,filename):
        """读取json文件"""
        with open(filepath+"/"+filename,"r") as json_file:
            data = json_file.read()
            users=json.loads(data)
            print (users)

    def read_ini(self,filepath,filename,section,options):
        """读取ini文件"""
        """返回单个名称"""
        cf =configparser.ConfigParser()
        cf.read(filepath+"/"+filename)
        cf.options(section=section)
        return cf.get(section,options)

    def read_ini_section(self,filepath,filename,section):
        """返回所有键值对"""
        cf =configparser.ConfigParser()
        cf.read(filepath+"/"+filename)
        items= dict(cf.items(section=section))
        return items

 

posted @ 2021-11-23 16:39  爱吃橙子_09  阅读(53)  评论(0)    收藏  举报