day17

os库提供文件管理操作

1.数据本地化和数据持久化 -- 通过文件将数据存到硬盘中
数据库文件、txt、json、plist、xml、png、mp3、mp4

2.文件操作 -- 文件内容操作
基本步骤:打开文件 --> 操作文件(读/写) --> 关闭文件
1)打开文件
'''
open(file,mode,encoding=None)

file -- 字符串,需要打开的文件的路径
./ -- 当前文件所在目录(./可以省略)
../ -- 当前文件所在目录的上层目录

mode -- 字符串,打开方式
r -- 默认值,以读的方式打开文件(只能进行读操作),读出来的是文本
w -- 以写的方式打开文件(只能进行写操作),覆盖
a -- 以写的方式打开文件(只能进行写操作),追加
rb/br -- 以读的方式打开文件(只能进行读操作),读出来的内容是二进制数据
wb/bw -- 以写的方式打开文件(只能进行写操作),将二进制数据写入文件中
+ -- 以读写的方式打开

encoding -- 文本编码方式
utf - 8
gbk
注意:文本编码只针对文本文件,二进制文件不能设置编码方式

'''

  1. 文件操作
    '''
    文件对象.read() -- 从读写位置开始,读到文件结尾,并且返回
    (读写位置默认在文件开头)

文件对象.seek(字节数) -- 将读写位置移动到文件的指定位置
'''

def main():
    # ============================1.文件读操作
    # 1) read
    f = open('./test.txt','r',encoding='utf-8')
    result = f.read(3)
    print(result)

    # 将光标移动到开头
    f.seek(0)
    result2 = f.read()
    print('=====:',result2)

    # 2)readline
    f.seek(0)
    print('读一行:',f.readline())


    f.seek(0)
    n = 0
    while True:
        result = f.readline()
        if result=='':
            break
        n += 1
        print('第%d行:' % n, result)

    # 3)readlines:一行一行读所有,列表
    f.seek(0)
    print(f.readlines())

    # ================================2.文件写操作
    '''
    文件对象.write(写的内容)  --  将指定内容写入到指定文件中,返回的是被写入内容的长度
    '''
    f = open('./test.txt', 'w', encoding='utf - 8')
    result = f.write('床前明月光')
    print(result)

    # 关闭文件
    f.close()

    # ================================
    '''
    注意:打开文件的时候,如果以读的方式打开一个不存在的文件,会报错;
          如果以写的方式打开一个不存在的文件,不会报错,并且会自动创建对应的文件再打开
    '''
    f1 = open('./test1.txt', 'w', encoding='utf-8')

1.二进制文件操作

'''
rb -- 读的时候获取到的是二进制数据(bytes)
wb -- 写的时候写入的内容要求类型是二进制文件

普通的文本文件可以通过二进制的形式去打开,影响只是获取到的内容,和写进去的内容的数据类型;
二进制文件只能以二进制的形式打开(例如:图片、视频、音频等)
'''

2.二进制数据

'''
一般二进制数据都是通过网络请求获取到,或者通过读取本地的二进制文件来取到

1)将字符串转换二进制
bytes(字符串, encoding = 'utf-8')
字符串.encode(encoding = 'utf-8')

2)将二进制转换成字符串
str(二进制数据,编码方式)
二进制数据.decode(编码方式)
'''

3.文件上下文

'''
with open(文件路径,打开方式,编码方式)as 文件对象:
操作文件

文件操作完成后,会自动关闭
'''

def main():

with open('./test.txt','r',encoding='utf-8')as f1:
    print(f1.read())

# 1.普通文本文件以二进制的形式打开
f = open('./test.txt', 'rb')
result = f.read()
print(result,type(result))

f.close()

f = open('./test.txt', 'wb')
f.write(bytes('aaa',encoding='utf-8'))

1.json数据

'''

  1. 满足json格式的数据就叫json数据

  2. json格式:一个json有且只有一个数据,这个数据必须是json支持的数据类型

  3. json支持的数据类型:
    数字(number) -- 包含所有的数字(整数和小数),支持科学计数法,例如:100,12.8,3e4
    字符串(string) -- 用双引号括起来的字符集,字符也可以是转义字符和编码字符,
    例如:"abc", "你好", "1234","abc\n123", "\u4e01abc"
    布尔(bool) -- true/false
    数组(array) -- 相当于python中的列表,[100, "abc", true, [1, 2, 3]]
    字典(dictionary) -- 相当于python中的字典,{"a":10 ,"b":56, "c":true}
    空值 -- null,相当于None

'''

2.使用json

'''

  1. 解析json数据(获取到json数据后,将json中想要的东西解析出来) -- 做前端开发人员的工作
  2. 构造json数据
    在python中有一个内置库,专门负责json数据的处理:json库
    1.1) 将json数据转换成python数据
    json数据 python数据
    number int/float
    string str,可能会出现将双引号变成单引号
    boolean bool,true --> True;false --> False
    array list
    dictionary dict
    null null --> None

1.2)loads方法
json.loads(字符串,encoding='utf-8') -- 解析json数据,返回json对应的python数据
字符串要求:字符串中的内容本身就是一个json数据(去掉引号后,本身就是一个json数据)

'''

# =====================1.json转python(json数据解析)
result = json.loads('"adc"',encoding='utf-8')
print(result,type(result))

result = json.loads('110.2',encoding = 'utf-8')
print(result,type(result))

result = json.loads('true',encoding = 'utf-8')
print(result,type(result))

result = json.loads('[10, 23, "yuting", true]',encoding = 'utf-8')
print(result,type(result))

result = json.loads('{"a": 100, "b": false}',encoding = 'utf-8')
print(result,type(result))


with open('./jsonData.json','r',encoding='utf-8')as f:
    content = f.read()
    content_py = json.loads(content,encoding='utf-8')
    data = content_py['data']
    max_dict = max(data, key=lambda x:int(x['favourite']))
    print(max_dict['name'],max_dict['text'],max_dict['favourite'])

# ====================2.python数据转换成json=====================
'''
2.1) python转json
python数据           json数据
int/float            number         
bool                 boolean,True -->true,False --> false
str                  string,将单引号变成双引号
list、tuple          array
dict                 dictionary
空值                 None --> null

2.2)
json.dumps(python数据)  -->  将python数据转换成内容是对应的json数据的字符串,结果是一个字符串
'''
result = json.dumps('abc')
print(type(result),result) # '"abc"'

result = json.dumps(['abc', 12, True, [1, 2], (1, 2), {'name': '小明', 'age': 18}, None])
print(type(result),result)

# ==========================3.json文件操作===============
'''
json.load(文件对象)  --  将文件对象中文件的内容转换成python数据,文件的数据是json数据

json.dump(python数据,文件对象)  --  将python数据转换成json字符串再写入指定文件中
'''
with open('./test.txt', 'r', encoding='utf-8') as  f:
    result = json.load(f)
    # result = json.loads(f.read(), encoding='utf-8')
    print(type(result),result)

with open('./test1.json', 'w', encoding='utf-8') as f:
    json.dump([100, True, 'abc'],f)
    # result = json.dumps([100, True, 'abc'])
    # f.write(result)

练习

import json
'''
1.数据怎么本地化?
每次需要这个数据的时候,不是直接给值,而是从本地文件中读取它的值
数据修改完后,需要将新的数据保存到本地文件中

2.什么时候需要用到json文件
需要持久化的数据是字典、列表、元祖
'''

# 练习1:每次运行程序的时候,打印当前是第几次运行这个程序
'''
with open('./test.txt','r',encoding='utf-8') as f:
    num = int(f.read())
    num += 1
    print(num)
with open('./test.txt','w',encoding='utf-8') as f:
    f.write(str(num))
'''

# 练习2:实现添加学生的功能,要求,之前添加的学生要一直存在
# class StudentsManage:
#     def __init__(self,name,age):
#         self.name = name
#         self.age = age
#         self.students = []
#     def add_student(self):
with open('./test.txt','r',encoding='utf-8')as f:
    students = json.load(f,encoding='utf-8')
def add_student():
    name = input('姓名:')
    age = int(input('年龄:'))
    stu = {'name': name, 'age': age}
    students.append(stu)

add_student()
add_student()

with open('./test.txt','w',encoding='utf-8')as f:
    #f.write(json.dumps(students))
    json.dump(students,f)

你可能感兴趣的:(day17)