面试题:
定义模块时可以把一个py文件或一个文件夹(包)当作一个模块,以方便于以后其他py文件的调用
对于包的定义:
模块的调用
def show(): print('卫斯理作者') def func(): pass print(456)
#导入模块 import lizhongwei print(123) #调用模块中的函数 lizhongwei.func()
导入模块 from lizhongwei import func,show from lizhongwei import * from lizhongwei import func func()
#导入模块 from lizhongwei import func as f def func(): print(123) f()
导入模块:
lizhong - jd.py - pdd.py - tb.py 包.py
import lizhong.jd lizhong.jd.f1()
from lizhong import jd jd.f1()
from lizhong.jd import f1 f1()
注意:sys.path的作用?
示例
import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR)
os
sys
time
json
dumps
loads
注意
import json v = {'k1':'alex','k2':'李杰'} val = json.dumps(v,ensure_ascii=False) print(val)
dump
import json v = {'k1':'alex','k2':'李杰'} f = open('x.txt',mode='w',encoding='utf-8') val = json.dump(v,f) print(val) f.close()
load
import json v = {'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,优点:所有语言通用;缺点只能序列化基本的数据类型 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(): pass v1 = pickle.dumps(f1) print(v1) v2 = pickle.loads(v1) print(v2) v2() ''' ###dump/load v = {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)
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 os import shutil from 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')
import time from 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) ###字符串转成datetime v1 = 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)
''' 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.写函数,函数接收一个列表,请将列表中的元素每个都+100 def func(arg): result = [] for item in arg: if item.isdecimal(): result.append(int(item) + 100) return result #2.写函数去接收一个列表,列表中都是url,请访问每个地址并获取结果。 import requests def 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'])
try: pass except Exception as e: pass