day-013--文件和异常

文件和异常

文件和异常我再前面已经搞了一波了,这个是大神的顺序,我把传送门放这

文件传送门
异常传送门

大概放些概念和补充知识在下面

1. 文件

在实际开发中,常常需要对程序中的数据进行持久化操作,而实现数据持久化最直接简单的方式就是将数据保存到文件中。说到“文件”这个词,可能需要先科普一下关于文件系统的知识,对于这个概念,维基百科上给出了很好的诠释,这里不再浪费笔墨。

2. 异常

为了让代码有一定的健壮性和容错性,我们可以使用Python的异常机制对可能在运行时发生状况的代码进行适当的处理,在Python中,我们可以将那些在运行时可能会出现状况的代码放在try代码块中,在try代码块的后面可以跟上一个或多个except来捕获可能出现的异常状况。例如在上面读取文件的过程中,文件找不到会引发FileNotFoundError,指定了未知的编码会引发LookupError,而如果读取文件时无法按指定方式解码会引发UnicodeDecodeError,我们在try后面跟上了三个except分别处理这三种不同的异常状况。最后我们使用finally代码块来关闭打开的文件,释放掉程序中获取的外部资源,由于finally块的代码不论程序正常还是异常都会执行到(甚至是调用了sys模块的exit函数退出Python环境,finally块都会被执行,因为exit函数实质上是引发了SystemExit异常),因此我们通常把finally块称为“总是执行代码块”,它最适合用来做释放外部资源的操作。如果不愿意在finally代码块中关闭文件对象释放资源,也可以使用上下文语法,通过with关键字指定文件对象的上下文环境并在离开上下文环境时自动释放文件资源
详细的看上面异常的传送门

3. json

这是个好东东,大部分可见的配置呀,http的协议,基本上都是json协议,所以这个是要学习一下:
json的字符串长这个样子:

{
    "name": "骆昊",
    "age": 38,
    "qq": 957658,
    "friends": ["王大锤", "白元芳"],
    "cars": [
        {"brand": "BYD", "max_speed": 180},
        {"brand": "Audi", "max_speed": 280},
        {"brand": "Benz", "max_speed": 320}
    ]
}

可以通过在线网站校验json格式有没有问题
传送门

刚开始是这样

image.png

正确的是这样的

image.png

错误的是这样的

image.png

会有提示,照着改就是了

3.1 json 和python格式对应关系

JSON Python
object dict
array list
string str
number (int / real) int / float
true / false True / False
null None
Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True / False true / false
None null

python 里有个json模块提供给我们用来json格式华操作,

json模块主要有四个比较重要的函数,分别是:

  • dump - 将Python对象按照JSON格式序列化到文件中
  • dumps - 将Python对象处理成JSON格式的字符串
  • load - 将文件中的JSON数据反序列化成对象
  • loads - 将字符串的内容反序列化成Python对象

实际操作一波:


import json

dict = {
    "name": "骆昊",
    "age": 38,
    "qq": 957658,
    "friends": ["王大锤", "白元芳"],
    "cars": [
        {"brand": "BYD", "max_speed": 180},
        {"brand": "Audi", "max_speed": 280},
        {"brand": "Benz", "max_speed": 320}
    ]
}
dict2 = {
    123:123
}
json_str = json.dumps(dict,ensure_ascii=False)
print(json_str)
load_str = json.loads(json_str)
print(load_str)
with open('json.txt','w',encoding='utf-8') as fjson:
    json.dump(dict,fjson,ensure_ascii=False)
    fjson.write('\n')
    json.dump(dict2, fjson)

with open('json.txt','r',encoding='utf-8') as fjson_r:
   for line in fjson_r:
       print(line)
       load_str = json.loads(line)
       print('load_str',load_str)

结果:

E:\learn100day\venv\Scripts\python.exe E:/learn100day/day013_home.py
{"name": "骆昊", "age": 38, "qq": 957658, "friends": ["王大锤", "白元芳"], "cars": [{"brand": "BYD", "max_speed": 180}, {"brand": "Audi", "max_speed": 280}, {"brand": "Benz", "max_speed": 320}]}
{'name': '骆昊', 'age': 38, 'qq': 957658, 'friends': ['王大锤', '白元芳'], 'cars': [{'brand': 'BYD', 'max_speed': 180}, {'brand': 'Audi', 'max_speed': 280}, {'brand': 'Benz', 'max_speed': 320}]}
{"name": "骆昊", "age": 38, "qq": 957658, "friends": ["王大锤", "白元芳"], "cars": [{"brand": "BYD", "max_speed": 180}, {"brand": "Audi", "max_speed": 280}, {"brand": "Benz", "max_speed": 320}]}

load_str {'name': '骆昊', 'age': 38, 'qq': 957658, 'friends': ['王大锤', '白元芳'], 'cars': [{'brand': 'BYD', 'max_speed': 180}, {'brand': 'Audi', 'max_speed': 280}, {'brand': 'Benz', 'max_speed': 320}]}
{"123": 123}
load_str {'123': 123}

文件里:

image.png

搞这个东东,中英文,还有一个文件多个json的时候,得注意

3.2 http请求中使用到的json

这里找了个请求天气的接口,返回的是json,千万不要死循环请求,会被关在小黑屋子里的。。。
请求http 用的requests模块,接口的传送门

直接上代码,只能查询城市的,省的查不了,县及其一下查不了。。。

import json
import requests

dict = {}
with open('city.json','r',encoding='utf-8') as fcity:
    json_str = json.load(fcity)
    for perjson in json_str:
        # print(perjson)
        dict[perjson['city_name']] = perjson['city_code']
# for key in dict.keys():
    #print(key, ':', dict[key])

while True:
    # inpuit_str = input('请输入要查询城市的天气:')
    inpuit_str = '北京'
    city_str = str(inpuit_str)
    if city_str in dict.keys():
        pass
        code_str = dict[city_str]
        if code_str is '':
            print('请输入具体城市,不要输入省份!')
        else:
            http_str = 'http://t.weather.sojson.com/api/weather/city/' + code_str
            print(http_str)
            resp = requests.get(http_str)
            data_model = json.loads(resp.text)
            # print(data_model)
            json_data = data_model['data']
            # print(json_data)
            json_forecast = json_data['forecast']
            print(city_str,'今天天气:', json_forecast[0]['type'],', 风向:',json_forecast[0]['fx'], ', 风力:',
                  json_forecast[0]['fl'], ',温度:', json_forecast[0]['high'], ',', json_forecast[0]['low'] )
            exit(0)
    else:
        print('输入有误请重新输入!')

请输入要查询城市的天气:kunshan
输入有误请重新输入!
请输入要查询城市的天气:昆山
输入有误请重新输入!
请输入要查询城市的天气:苏州
http://t.weather.sojson.com/api/weather/city/101190401
苏州 今天天气: 多云 , 风向: 西北风 , 风力: <3级 ,温度: 高温 32.0℃ , 低温 26.0℃

city.json 去这儿下载:链接: https://pan.baidu.com/s/1JFAwnH2MRLc5OD3hsJZwGQ 提取码: u8sk
如果链接失效就去网站看看,不行就联系我。。。下载之后名字改成city.json,和python文件一个目录就行

文集传送门 学习python100天


整个学习python100天的目录传送门


无敌分割线


再最后面附上大神的链接
传送门

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容