栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

继承json和csv文件操作

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

继承json和csv文件操作

1. 继承 1.1 继承

继承 - 让子类直接拥有父类的属性和方法。

子类 - 继承者;
父类 - 被继承者;
关系:父类拥有的东西,子类都有,但是子类除了有父类的东西以外还有一些额外特有的东西。

class Person:
    def __init__(self):
        self.name = '小明'
        self.age = 18
        self.gender = '男'

    def eat(self):
        print('吃饭')

    def sleep(self):
        print('睡觉')


# class Student:
#     def __init__(self):
#         self.name = '小明'
#         self.age = 18
#         self.gender = '男'
#         self.study_id = '001'
#
#     def eat(self):
#         print('吃饭')
#
#     def sleep(self):
#         print('睡觉')
#
#     def study(self):
#         print('学习')
1.2 继承的作用

子类是可以继承父类所有的内容(包括:类属性、对象属性、对象方法、类方法、静态方法)。

"""
class 类名(父类):
    说明文档
    类的内容
"""


class Student(Person):
    pass


stu = Student()
print(stu.name, stu.age, stu.gender)
stu.eat()
stu.sleep()
class A:
    x = 123

    def __init__(self):
        self.m = 10
        self.n = 20

    def func1(self):
        print('对象方法')

    @classmethod
    def func2(cls):
        print('类方法')

    @staticmethod
    def func3():
        print('静态方法')


class B(A):
    pass


b = B()
print(b.m)
b.func1()

print(B.x)
B.func2()
B.func3()
1.3 在子类中添加 1.3.1 添加类属性和添加方法

直接在子类中定义新的类属性和新的方法。

1.3.2 在子类中添加对象属性

需要在子类的__init__方法中通过super()去调用父类的__init__方法来继承父类的对象属性。

class Person:
    def __init__(self):
        print('========Person中的init方法========')
        self.name = '小明'
        self.age = 18
        self.gender = '男'

    def eat(self):
        print('吃饭')

    def sleep(self):
        print('睡觉')


class Teacher(Person):
    profession = '老师'

    def attend_class(self):
        print('上课')

    # def __init__(self):
        # 主动调用父类的__init__方法去继承父类的对象属性
        # super()  -  获取当前父类的对象属性
        super().__init__()
        print('========Teacher中的init方法========')
        self.title = '副教授'


print(Teacher.profession)

t1 = Teacher()
t1.eat()
t1.sleep()
t1.attend_class()

print(t1.name, t1.age, t1.gender)
print(t1.title)
1.4 super的用法

1)super() - 获取当前类的父类;

2)super(类, 对象) - 获取指定类的父类(后面的这个对象必须是前面的类的对象)。

3)def _repr_(self):打印当前类的对象的时候就会自动调用这个方法,打印的是谁,self就是谁。打印结果就是这个函数的返回值(必须是字符串)。

# object  -  python所有类的基类
class A(object):
    def __init__(self):
        self.a = 10


class B(A):
    def __init__(self):
        self.b = 20


class C(B):
    def __init__(self):
        self.c = 30


class D(C):
    def __init__(self):
        # 1.调用当前类的父类的__init__
        # super().__init__()
        # super(D, self).__init__()

        super(C, self).__init__()   # C的父类
        self.d = 40


dd = D()
print(dd.d)
# print(dd.c)
print(dd.b)



class Person:
    def __init__(self, name, age=18, gender='男'):
        self.name = name
        self.age = age
        self.gender = gender


class Student(Person):

    def __init__(self, study_id, name, age=18, gender='男'):
        super().__init__(name, age, gender)
        self.study_id = study_id

    # 打印当前类的对象的时候就会自动调用这个方法,打印的是谁,self就是谁。打印结果就是这个函数的返回值(必须是字符串)。
    def __repr__(self):
        # return f'学号:{self.study_id}, 姓名:{self.name}, 年龄:{self.age}, 性别:{self.gender}'
        return str(self.__dict__)


stu1 = Student('stu001', '李华')
print(stu1)

stu2 = Student('stu002', '张三')
print(stu2)
2. json数据 2.1 json的作用

1)json是一种通用的数据格式,主要用于不同编程语言之间进行有效的数据交流;

2)xml是另外一种通用的数据格式;json更小更快;xml更安全。

2.2 json数据格式 2.2.1 json数据格式的要求

1)一个json有且只有一个数据;

2)唯一的这个数据必须是json支持的数据类型的数据。

2.2.2 json支持的数据类型

1)数字 - 包括整数和小数,表示的时候直接写:28、2.32、-56、3e5;

2)字符串 - 双引号引起来的数据(支持转义字符):“fdn”、“123”、“tabcn123u4e00”;

3)布尔 - 只有true和false;

4)数组 - 相当于列表:[元素1, 元素2, 元素3,…];

5)字典 - 相当于python的字典(键必须是字符串):{键1:值1, 键2:值2,…};
6)空值 - null 。

2.3 python数据和json数据之间的相互转换
# python中json模块中包含了:loads、dump

from json import loads,dumps
from re import findall
2.3.1 json转python文件

1)loads(json格式的字符串) - 将json数据转换成对应的python数据;

2)说明:json格式的字符串 - 字符串内容是json数据的字符串(去掉字符串外面的引号后是一个合法的json数据)。

json -> python
数字 -> int、float
字符串 -> str(会将双引号变成单引号)
布尔 -> true -> True; false -> False
空值 -> null -> None
数组 -> list
字典 -> dict

result = loads('"abc"')
print(result)    # 'abc'

result = loads('100')
print(result,type(result))    # 100 

result = loads('true')
print(result)    # True

result = loads('[100,"abc",true,null]')
print(result)    # [100, 'abc', True, None]

练习:基于data.json文件,提取所有新闻的标题。

json_data = open('data.json',encoding='utf-8').read()

# 方法1:使用正则
result = findall(r'(?s)"title":s*"(.+?)",', json_data)
print(result)

# 方法2:json解析
python_data = loads(json_data)
for x in python_data['newslist']:
    print(x['title'])
2.3.2 python转json

dumps(python数据) - 将指定的python数据转换成对应的json格式的字符串。

python -> json
int、float -> 数字
str -> 字符串(单引号变双引号)
bool -> True -> true、False -> false
None -> None -> null
list、tuple -> 数组
dict -> 字典

dumps(100)   # '100'
dumps('abc')  # "abc"
dumps(True)   # 'true'

result = dumps({'a':20, 30:'小明', 'b': [1.23, False, None]})
print(result)    # '{"a": 20, "30": "u5c0fu660e", "b": [1.23, false, null]}'

result = dumps((10, 'abc', True, None))
print(result)    # '[10, "abc", true, null]'
3. csv文件读操作
import csv
3.1 创建reader获取文件内容 3.1.1 csv.reader(文件对象)

csv.reader(文件对象) - 返回一个迭代器,迭代器中的元素就是每一行内容对应的列表。

3.1.2 csv.DictReader(文件对象)

csv.DictReader(文件对象) - 返回一个迭代器,迭代器中的元素就是每一行内容对应的字典(第一行数据是键)。

data = csv.reader(open('files/2018年北京积分落户数据.csv',encoding='utf-8',newline=''))

data2 = csv.DictReader(open('files/2018年北京积分落户数据.csv',encoding='utf-8',newline=''))
3.2 获取迭代器中的内容
print(next(data))
print(next(data))
print(next(data))

print(next(data2))
3.3 练习

练习:计算积分平均分。

data2 = csv.DictReader(open('files/2018年北京积分落户数据.csv',encoding='utf-8',newline=''))
scores = [eval(x['score']) for x in data2]
print('平均分:', f'{sum(scores) / len(scores):.2f}')
4. csv文件写操作
import csv
4.1 以列表为单位写入数据 4.1.1 创建writer

创建writer:csv.writer(文件对象)。

writer = csv.writer(open('files/students.csv','a',encoding='utf-8',newline=''))
4.1.2 写入数据

1)一次写一行;

writer.writerow(['name', 'age', 'gender', 'tel', 'score'])
writer.writerow(['小明', 18, '男', '110', '98'])

2)同时写入多行数据;

writer.writerows([
    ['小花', 22, '女', '123', 95],
    ['小明', 25, '男', '125', 90],
    ['小白', 20, '女', '120', 85]
])
4.2 以字典为单位写入数据 4.2.1 创建writer

创建writer:csv.DictWriter(文件对象,键对应的列表)。

writer = csv.DictWriter(
    open('files/students2.csv','w',encoding='utf-8',newline=''), ['name', 'age', 'gender', 'tel', 'score'])
4.2.2 写入数据

1)写入头部数据(将字典的键直接写入到第一行);

writer.writeheader()

2)一次写一行;

writer.writerow({'name': '小明', 'age': 29, 'gender': '男', 'tel': '123', 'score': 98})

3)同时写入多行;

writer.writerows([
    {'name': '小明', 'age': 29, 'gender': '男', 'tel': '123', 'score': 98},
    {'name': '小花', 'age': 19, 'gender': '女', 'tel': '122', 'score': 88},
    {'name': '小黑', 'age': 22, 'gender': '男', 'tel': '125', 'score': 78}
])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/864265.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号