摘要
书接前文:
01-《零基础编程——起步并搭建Python环境》
02-《零基础编程——变量与数据类型》
03-《零基础编程——Python循环、函数、类》
教程使用的还是《Python编程入门到实战》(参考:https://s.click.taobao.com/3AFvciv)
本文将讲解Python文件、JSON、网络、线程
一 文件操作
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())))
二 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数据存储。