dump文件_零基础编程——Python文件、JSON数据存储

摘要

书接前文:

01-《零基础编程——起步并搭建Python环境》

02-《零基础编程——变量与数据类型》

03-《零基础编程——Python循环、函数、类》

教程使用的还是《Python编程入门到实战》(参考:https://s.click.taobao.com/3AFvciv)

本文将讲解Python文件、JSON、网络、线程


c76a8097e4732a7a9d1e6c626addc096.png

一 文件操作

1-文件读取

#读取文件,全部输出(with的这种方式,会自动close()释放资源)filePath = 'D:DevPythonWorksPythonPrimedata.csv'with open(filePath) as f_csv:    context = f_csv.read()    print("-:"+context)#读取文件,逐行输出(with的这种方式,会自动close()释放资源)with open(filePath) as f_csv:    for line in f_csv:        print("-:"+line.rstrip())#并去掉空格

2-文件写入

filePath = 'D:DevPythonWorksPythonPrimeinput.txt'yourContext1 = input("请输入第1行,输完按回车键")yourContext2 = input("请输入第2行,输完按回车键")#异常处理try:    #1-写文件,写入一行数据,并    with open(filePath,'w',encoding='gbk') as fTxt:        fTxt.write(yourContext1+"")#""换行        fTxt.write(yourContext2+"")        print("替换写入-完成")    #2-写文件,追加数据    with open(filePath,'a',encoding='gbk') as fTxt:        fTxt.write(yourContext1 + "")        fTxt.write(yourContext2 + "")        print("追加写入-完成")    #3-输出文件,逐行输出    with open(filePath) as fTxt:        for line in fTxt:            print("-:"+line.rstrip())#并去掉空格except Exception as es:    print(es)else:    print('end')    print(str(len(yourContext1.split())))
7ead5fce2d0f645a22c275d4d15a2ab8.png

二 JSON数据

1-json数据格式读写:json.dump(),json.load()

import  json##json格式是一种数据规范格式##json.dump()存储数据,格式json存储格式filePath = 'D:DevPythonWorksPythonPrimedata.json'number = [1,12,3,4,5,6,7,7,8]#需要存储的with open(filePath,'w') as f:    json.dump(number,f)##json.load() 数据读取with open(filePath) as f:    ctx = json.load(f)    print(ctx)

一般用于存储临时数据,例如网站登录用户信息json临时保存等。

2-json数据格式转换:json.dumps(),json.loads()

import  jsondata = {    'name' : 'ACME',    'shares' : 100,    'price' : 542.23}jsonStr = json.dumps(data)#Python数据结构转json字符串jsonData = json.loads(jsonStr)#json字符串转Python数据结构print(type(data))print(type(jsonStr))print(type(jsonData))

三 总结

掌握文件读写,json数据存储。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值