文本操作和json操作基础

1.数据本地化和数据持久化 - 通过文件将数据存到硬盘中

  • 数据库文件、txt、json、plist、xml、png文件、MP4、mp3等

2.文件操作 - 文件内容操作

  • 基本步骤: 打开文件 --> 操作文件(读/写) --> 关闭文件

1)打开文件

open(file, mode, encoding=None) - 以指定方式打开指定文件,并且返回被打开的文件对象

file  -- 字符串,需要打开的文件的路径
         ./   --  当前文件所在目录(./可以省略)
         ../  --  当前文件所在目录的上层目录
   
mode  -- 字符串,打开方式
         r   --  默认值,以读的方式打开文件(只能进行读操作), 读出来的是文本
         w   --  以写的方式打开文件(只能进行写操作), 覆盖
         a   --  以写的方式打开文件(只能进行写操作), 追加
         rb/br  -- 以读的方式打开文件(只能进行读操作),读出来的内容是二进制数据
         wb/bw  -- 以写的方式打开文件(只能进行写操作),将二进制数据写入文件中
         +   --   以读写的方式打开(了解)
         
encoding  -- 文本编码方式  
             utf-8  
             注意:文本编码只针对文本文件、二进制文件不能设置编码方式

2)文件操作

  • 文件对象.read() – 从读写位置开始,读到文件结尾,并且返回
    (读写位置默认在文件开头)

  • 文件对象.seek(字节数) – 将读写位置移动到指定的地方(了解)

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

    # 将读写位置移动到文件开头
    f.seek(0)
    result = f.read()
    print('====:', result)

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

    # 练习: 一行一行的将文件中的内容读完
    f.seek(0)
    while True:
        result = f.readline()
        if not result:
            break

        print(result)

    # 3)readlines:一行一行读所有,列表
    f.seek(0)
    print(f.readlines())
    f.close()
    # ================2.文件写操作==================
    文件对象.write(写的内容)   - 将指定内容写入到指定文件中,返回被写入的内容的长度
    f = open('./files/test.txt', 'w', encoding='utf-8')
    result = f.write('abc')
    print(result)

    # 关闭文件
    f.close()
  • 注意: 打开文件的时候,如果以读的方式打开一个不存在的文件,会出现异常,报错
  • 如果以写的方式打开一个不存在的文件,不会出现异常,并且会自动创建对应的文件再打开
    f1 = open(’./files/test4.txt’, ‘w’, encoding=‘utf-8’)

1.二进制文件操作

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

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

2.二进制数据

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

1)将字符串转换二进制
bytes(字符串, 编码方式)
字符串.encode(编码方式)

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

3.文件上下文

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

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

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

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

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

    # 2. 二进制文件
    f1 = open('./files/luffy4.jpg', 'rb')
    reslut = f1.read()
    print(reslut, type(reslut))

    f2 = open('./files/aaa.jpg', 'wb')
    f2.write(reslut)

if __name__ == '__main__':
    main()

import json

1.json数据

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

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

3)json支持的数据类型:
数字(number) - 包含所有的数字(整数和小数),支持科学计数法,例如:100, 12.8, 3e4
字符串(string) - 用双引号括起来的字符集,字符也可以是转义字符和编码字符,
例如: “abc”, “你好”, “12334”,“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 -> None

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

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

result = json.loads('100.12', 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()
    # print(type(content), content)
    content_py = json.loads(content, encoding='utf-8')
    # print(type(content_py),content_py)
    data = content_py['data']
    # print(type(data), data)
    # for dict1 in data:
    #     print(dict1['name'])
    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(100)
print(type(result), result)

result = json.dumps('abc')
print(type(result), result)    # '"abc"'

result = json.dumps(True)
print(type(result), result)     # 'true'

result = json.dumps([12, 'abc', [1, 2], True])
print(type(result), result)     # '[12, "abc", [1, 2], true]'

result = json.dumps((12, True, 'abc', (1, 2)))
print(type(result), result)     # '[12, true, "abc", [1, 2]]'

# result = json.dumps({12, 34, 5})
# print(type(result), result)     # TypeError: Object of type 'set' is not JSON serializable

result = json.dumps({'name': '小明', 'age': 18})
print(type(result), result)    # {"name": "\u5c0f\u660e", "age": 18}

3.json文件操作(了解)=
json.load(文件对象) - 将文件对象中文件的内容转换成python数据
文件的内容只能是json数据(文件后缀没有要求)

json.dump(python数据,文件对象) – 将python数据转换成json字符串再写入指定文件中

with open('./files/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('./test2.json', 'w', encoding='utf-8') as f:
    json.dump([100, True, 'abc'], f)

    # result = json.dumps([100, True, 'abc', None])
    # f.write(result)

import json

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

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

###练习1: 每次运行程序的时候,打印当前是第几次运行这个程序

with open('./files/test.txt', 'r', encoding='utf-8') as f:
    num = int(f.read())
    num += 1
    print(num)

with open('./files/test.txt', 'w', encoding='utf-8') as f:
    f.write(str(num))

###练习2: 实现添加学生的功能,要求,之前添加的学生要一直存在

with open('./files/students.txt', 'r', encoding='utf-8') as f:
    # students = json.loads(f.read())
    students = json.load(f)

def add_student():
    name = input('姓名:')
    age = input('年龄:')
    stu = {'name': name, 'age':int(age)}
    students.append(stu)

add_student()
add_student()

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

print(students)

def main():
    pass

if __name__ == '__main__':
    main()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值