如果导入的模块不存在,Python解释器会报 ModuleNotFoundError 错误,一般通过 pip install xxx(模块名) 下载就可以了
有时两个不同的模块提供了相同的功能,比如 StringIO 和 cStringIO 都提供了StringIO这个功能。
这是因为Python是动态语言,解释执行,因此Python代码运行速度慢。
如果要提高Python代码的运行速度,最简单的方法是把某些关键函数用 C 语言重写,这样就能大大提高执行速度。
同样的功能,StringIO 是纯Python代码编写的,而 cStringIO 部分函数是 C 写的,因此 cStringIO 运行速度更快。
利用ModuleNotFoundErrorr错误,经常在Python中动态导入模块:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
上述代码先尝试从cStringIO导入,如果失败了(比如cStringIO没有安装),再尝试从StringIO导入。这样,如果cStringIO模块存在,则我们将获得更快的运行速度,如果cStringIO不存在,则顶多代码运行速度会变慢,但不会影响代码的正常执行。
拓展1: try 的作用是捕获错误,并在捕获到指定错误时执行 except 语句。
任务:
利用import … as …,动态导入不同名称的模块。
Python 自2.6版本及以后提供了json 模块,但Python 2.5以及更早版本没有json模块,不过可以通过安装simplejson模块,这两个模块提供的函数签名和功能都一模一样。
写出导入json 模块的代码,能在Python 2.5及目前版本上都能正常运行。
try:
import simplejson as json
except ImportError:
import json
print(json.dumps({'python': 3.6}))
结果为: {“python”: 3.6}
拓展2:
Python中的 json 模块提供了一种很简单的方式来编码和解码JSON数据。 其中两个主要的函数是 json.dumps() 和 json.loads()。
- json.dumps可以将一个Python数据结构转换为JSON:
栗子1:
import json
data = {
'name': 'guoguo',
'age': 10,
}
json_str = json.dumps(data)
print(json_str)
结果为: {“name”: “guoguo”, “age”: 10}
- json.loads将一个JSON编码的字符串转换回一个Python数据结构:
栗子2:
import json
data = {
'name': 'guoguo',
'age': 10,
}
# Python--> Json
json_str = json.dumps(data)
print('This is json_str data structure-->', json_str)
# Json-> Python
data = json.loads(json_str)
print('This is python data structure-->', data)
结果为: This is json_str data structure–> {“name”: “guoguo”, “age”: 10}
This is python data structure–> {‘name’: ‘guoguo’, ‘age’: 10}
- json.dump() 和 json.load() 来编码和解码JSON数据,用于处理文件
栗子3:
with open('test.json', 'w') as f:
json.dump(data, f)
with open('test.json', 'r') as f:
data = json.load(f)
大家加油!
学习链接: https://www.imooc.com/code/6071
https://blog.youkuaiyun.com/lizhixin705/article/details/82344209
1441

被折叠的 条评论
为什么被折叠?



