Json库和文件操作

文章目录

JSON

python 复制代码
import json

#json常用的只有4个方法,不带s的是序列化到文件或者从文件反序列化,带s的都是内存操作不涉及持久化
json.load()   # 从文件中读取json字符串 -->python对象
json.loads()  # json字符串 ->python对象
json.dump()   # python对象转化为json字符串写入文件中
json.dumps() # python 对象 -> json字符串


with open('json_test.txt','w+') as f:
    json.dump(data,f)
 
with open('json_test.txt','r+') as f:
    print(json.load(f))


ps:元组和列表解析出来的均是数组

文件操作

with 表示会自动在读写文件后关闭流,常用模式r,w,a

r : 读取文件,若文件不存在则会报错

w: 写入文件,若文件不存在则会先创建再写入,会覆盖原文件

a : 写入文件,若文件不存在则会先创建再写入,但不会覆盖原文件,而是追加在文件末尾

rb,wb:分别于r,w类似,但是用于读写二进制文件

r+ : 可读、可写,文件不存在也会报错,写操作时会覆盖

w+ : 可读,可写,文件不存在先创建,会覆盖

a+ :可读、可写,文件不存在先创建,不会覆盖,追加在末尾

python 复制代码
# 1.写文件
with open("a.txt","w") as f:
    json.dumps(data,f)
# 2.读文件
with open("a.txt","r") as f:
    json.loads(data,f)
# 3.逐行写文件
with open("a.txt","w") as f:
    f.writeLines(data+"\n")
# 4.逐行读文件
with open("a.txt","r") as f:
    for line in f:
        dosomething
相关推荐
wtsolutions8 小时前
JSON to Excel Add-in - Seamless Integration Within Excel
json·excel
wtsolutions8 小时前
Getting Started with JSON to Excel Web App - Convert in Seconds
json·excel·web app
晚风吹长发8 小时前
初步了解Linux中的动静态库及其制作和使用
linux·运维·服务器·数据结构·c++·后端·算法
梁下轻语的秋缘9 小时前
ESP32-WROOM-32E存储全解析:RAM/Flash/SD卡读写与速度对比
java·后端·spring
wanzhong23339 小时前
开发日记8-优化接口使其更规范
java·后端·springboot
羊小猪~~10 小时前
【QT】--文件操作
前端·数据库·c++·后端·qt·qt6.3
张彦峰ZYF11 小时前
商品供给域的工程化简要设计考量
后端·系统架构·商品模型·商品供给
wtsolutions12 小时前
Using the JSON to Excel API - Programmatic Access for Developers
json·excel
小北方城市网12 小时前
微服务注册中心与配置中心实战(Nacos 版):实现服务治理与配置统一
人工智能·后端·安全·职场和发展·wpf·restful
爬山算法13 小时前
Hibernate(47)Hibernate的会话范围(Scope)如何控制?
java·后端·hibernate