面试题:
列举常用第三方模块:Json/time/ /os/sys定义模块定义模块时可以把一个py文件或一个文件夹(包)当作一个模块,以方便于以后其他py文件的调用
对于包的定义:
py2:文件夹中必须有_ _ ini t_ _.py文件py3:不需要_ _ ini t_ _.py文件模块的调用
示例一def show(): print('卫斯理作者')def func(): passprint(456)
#导入模块import lizhongweiprint(123)#调用模块中的函数lizhongwei.func()
导入模块from lizhongwei import func,showfrom lizhongwei import *from lizhongwei import funcfunc()
#导入模块from lizhongwei import func as fdef func(): print(123) f()
导入模块:
import 模块 模块 函数()from 模块 import 函数 函数()from 模块 import 函数 as 别名 别名()示例二:lizhong - jd.py - pdd.py - tb.py包.py
import lizhong.jdlizhong.jd.f1()
from lizhong import jdjd.f1()
from lizhong.jd import f1f1()
总结模块和要执行的py文件在同一目录 且 需要模块中很多功能时,推荐用:import 模块其他推荐:from 模块 import 模块 模块.函数()其他推荐:from 模块.模块 import 函数 函数()注意:sys.path的作用?
示例
import osimport sysBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(BASE_DIR)
内置模块os
sys
time
Json
dumps
loads
注意
字典或列表中如有中文,序列化时想要保留中文显示import Jsonv = {'k1':'alex','k2':'李杰'}val = Json.dumps(v,ensure_ascii=False)print(val)
dump
import Jsonv = {'k1':'alex','k2':'李杰'}f = open('x.txt',mode='w',enCoding='utf-8')val = Json.dump(v,f)print(val)f.close()
load
import Jsonv = {'k1':'alex','k2':'李杰'}f = open('x.txt',mode='r',enCoding='utf-8')val = load(f)f.close()print(val,type(val))
hashlib
random
getpass
shutil
copy
今日内容Json和pickleJson,优点:所有语言通用;缺点只能序列化基本的数据类型 List/dict/int
pickle,优点:python中所有的东西都能被序列化(socket对象);缺点:序列化的内容只有Python认识,其他语言不认识。
import pickle###dumps/loads'''v = {1,2,3,4}val = pickle.dumps(v)print(val)data = pickle.loads(val)print(data)''''''def f1(): passv1 = pickle.dumps(f1)print(v1)v2 = pickle.loads(v1)print(v2)v2()'''###dump/loadv = {1,2,3,4}f1 = open('x.txt',mode='wb')val = pickle.dump(v,f1)f1.close()f = open('x.txt',mode='rb')data = pickle.load(f)f.close()print(data)
shutil模块import shutil#删除目录# shutil.rmtree('test')#重命名# shutil.move('x.txt','xxx.txt')#压缩文件# shutil.make_archive('zzh','zip','D:\code\s21day16')#解压文件shutil.unpack_archive('zzh.zip',extract_dir=r'D:\code\xxx,format='zip')
示例:import osimport shutilfrom datetime import datetime#1.压缩lizhongwei文件夹zip#2.放到code目录(默认不存在)#3.将文件解压到D:\x1目录中。ctime = datetime.Now().strftime('%Y-%m-%d-%H-%M-%s')print(ctime)if not os.path.exists('code'): os.makedirs('code')shutil.make_archive(os.path.join('code',ctime),'zip','D:\code\s21day16\lizhongwei')file_path = os.path.join('code',ctime) + '.zip'shutil.unpack_archive(file_path,r'D:\x1','zip')
time & datetimetime模块time.time() ,时间戳:1970-1-1 00:00time.sleep(10),等待秒数time.timezonedatetime模块import timefrom datetime import datetime,timezone,timedelta###获取datetime格式时间'''v1 = datetime.Now() #当前本地时间print(v1)v2 = datetime.utcNow() #当前UTC时间print(v2)tz = timezone(timedelta(hours=7)) #当前东7区时间v3 = datetime.Now(tz)print(v3)'''###把datetime格式转换成字符串# v1 = datetime.Now()# print(v1,type(v1))# val = v1.strftime('%Y-%m-%d %H:%M:%s')# val = v1.strftime('%y-%m-%d %H:%M:%s')# print(val)###字符串转成datetimev1 = datetime.strptime('2011-11-11','%Y-%m-%d')print(v1,type(v1))###datetime时间的加减v1 = datetime.strptime('2011-11-11','%Y-%m-%d')print(v1,type(v1))v2 = v1 + timedelta(days=140)print(v2)###时间戳和datetime关系ctime = time.time()print(ctime)v1 = datetime.fromtimestamp(ctime)print(v1)
logging异常处理'''try: val = input('请输入数字:') num = int(val)except Exception as e: print(' *** 作异常')'''# import requests# try:# ret = requests.get('http://www.baIDu.com')# print(ret.text)# except Exception as e:# print('请求异常')def func(a): try: a.strip() except Exception as e: pass return False# v = func('alex')v = func([11,22,33])# print(v)if not v: print('函数执行失败')else: print('结果是',v)
练习题
#1.写函数,函数接收一个列表,请将列表中的元素每个都+100def func(arg): result = [] for item in arg: if item.isdecimal(): result.append(int(item) + 100) return result#2.写函数去接收一个列表,列表中都是url,请访问每个地址并获取结果。import requestsdef func(url_List): result = [] try: for url in url_List: response = requests.get(url) result.append(response.text) except Exception as e: pass erturn result def func2(url_List): result = [] for url in url_List: try: response = requests.get(url) result.append(response.text) except Exception as e: pass erturn result func(['http://www.baIDu.com','http://www.Google.com','http://www.bing.com'])
总结函数高级 5*嵌套装饰器模块分类和自定义 4*内置模块ossys第三方requestsxlrd自定义模块文件文件夹 + init.py(包)导入模块sys.path导入importfrom xx.xxx import xx异常处理try: passexcept Exception as e: pass
总结 以上是内存溢出为你收集整理的Python学习笔记:day16 模块基础知识(time\datetime\json\picle\shutil\logging)全部内容,希望文章能够帮你解决Python学习笔记:day16 模块基础知识(time\datetime\json\picle\shutil\logging)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)