python内置模块笔记(持续更新)
QQ群:397745473
python 常用模块 常用函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 name = '{wh}my \t name is {name},age is {age}.' print (name.capitalize()) print (name.center(100 , "+" )) print (name.endswith("." )) print (name.expandtabs(30 )) print (name.find("n" )) print (name.index("n" )) print (name.count("z" )) print (name.format (wh="nihao," , name="1233" , age=100 )) print ('{:^10},{:6}' .format ('username' , 'password' )) print (name.format_map({'wh' : 'huanying,' , 'name' : 'xiaoming' , "age" : "19" })) print ("sadads12313#$" .isalnum()) print ("123" .isalpha()) print ("abc" .isdigit()) print (name.decimal()) print ("#¥&*……&*" .isidentifier()) print ("asdadA" .islower()) print ("name" .isupper()) print ("@#@$#@QsaddsadS Sad " .istitle()) print ("___" .join([name, "enen" , "oo" ])) print ("SAHD #@OAHDa sd ad" .lower()) print ("sahdk" .upper()) print (' \t \nmysql\t\n' .lstrip()) print (' \t \nmysql\t\n ' .rstrip()) print (' \t \nmysql\t\n ' .strip()) print (" kongge " .isspace()) print (" dasds " .split()) print (name.splitlines()) print ("mysql is db" .replace("mysql" , "oracle" )) print ("mysql is dbisis" .rfind("is" )) print ("1+2+3+4" .split("+" )) print ("1+2+3+4\n5+6+7+8" .splitlines()) print ("abcABC" .swapcase()) print ("1" .zfill(2 )) print (name.endswith("{age}." )) print (name.startswith("{age}." )) print (bin (12 )) print (name.ljust(50 , '*' )) str1 = "Runoob example....wow!!!" l = "12345" r = "abcde" res = str1.maketrans(r, l) print (str1.translate(res)) print (max (name)) print (bool ('' )) print (round (3.1415926 , 2 )) print (sorted ([1 , 3 , 400 , 234 , 23 ], reverse=True )) print (any ([1 , 2 , 3 , 45 ])) print (all ([1 , 2 , 3 , 45 ])) print (dir (name)) print (eval ("1+1" )) print (exec ("print('nihao')" )) print (list (map (funcion, L))) print (list (filter (funcion, L))) print (getattr (对象, "函数名" )) print (hasattr (模块, 方法)) print (isintance(对象, 类))
数据类型转换 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 a = 1234 print (0x4d2 ) print (hex (a)) print (oct (a)) print (bin (a)) print ('asd' .encode()) print (b'asd' .decode()) print (chr (78 )) print (ord ('a' )) b = ["1234" , 23 , 23 , 213 , 21341 ] list (b) tuple (b) dist(b) int (a) float (a) res1 = set (b) res2 = frozenset (b) b_str = str (b) b_repr = repr (b)
random模块 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import randomprint (random.sample([1 , 3 , 4 , 5 , 6 ], 2 )) print (random.randrange(100 )) print (random.randrange(5 , 10 , 2 )) print (random.randint(1 , 3 )) print (random.random()) print (random.uniform(1.1 , 32.2 )) a = [1 , 23 , 4 , 5 , 6 , 7 ] print (random.choice(a)) random.shuffle(a) print (a) random.choices(population, weights=None , *, cum_weights=None , k=1 ) random.choices(["红球" , "黄球" , "篮球" , "黑球" ], [50 , 30 , 15 , 5 ], k=1 )
string模块 1 2 3 4 5 6 7 8 9 10 11 12 import stringstring.ascii_letters string.ascii_lowercase string.ascii_uppercase string.digits string.punctuation string.printable string.hexdigits string.octdigits string.whitespace
os模块 与操作系统进行交互
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 import osos.system('ls' ) os.getcwd() os.chmod("/local/upload/" , 7 ) os.chdir("../" ) os.curdir() os.pardir() os.makedir("/usr/local/tomcat" ) os.removedir("/usr/local/tomcat" ) os.mkdir("a" ) os.rmdir("a" ) os.remove("a.txt" ) os.listdir() os.rename("a" , "b" ) os.stat("a.py" ) print (os.sep) print (os.linesep) print (os.pathsep) print (os.environ) print (os.name) os.walk("路径" ) os.system('操作系统命令' ) os.popen('操作系统命令' ) print (os.path.abspath(__file__)) print (os.path.getsize('a.txt' )) print (os.path.split("/usr/hehe/hehe.txt" )) print (os.path.dirname("/usr/local" )) print (os.path.basename("/usr/local" )) print (os.path.exists("/usr/local" )) print (os.path.isabs("." )) print (os.path.isfile("/usr/local" )) print (os.path.isdir("/usr/local" )) print (os.path.join("/root" , 'hehe' , 'a.sql' )) print (os.path.getatime("len_os.py" )) print (os.path.getmtime("len_os.py" )) print (os.path.getctime("len_os.py" )) os.access("../test.html" , os.F_OK) os.access("../test.html" , os.R_OK) os.access("../test.html" , os.W_OK) os.access("../test.html" , os.X_OK) os.chown(path, uid, gid) os.chroot(path)
sys模块 与python解释器进行交互
1 2 3 4 5 6 7 8 9 10 11 import syssys.argv sys.exit(n) sys.version sys.maxint sys.path sys.platform sys.stdout.write('please:' ) val = sys.stdin.readline()[:-1 ]
time,datetime模块 时间有三种表示方式,一种是时间戳、一种是格式化时间、一种是时间元组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 import time, datetimeprint (time.timezone) print (time.time()) print (time.clock()) print (time.sleep(1 )) print (time.gmtime()) print (time.localtime()) print (time.mktime(time.localtime())) print (time.strftime("%y%m%d %H%M%S" )) print (time.strptime("20160204 191919" , "%Y%m%d %H%M%S" )) print (time.struct_time) print (time.asctime()) print (time.ctime()) print (datetime.datetime.now()) print (datetime.datetime.now() + datetime.timedelta(3 )) print (datetime.datetime.now() + datetime.timedelta(-3 )) time.asctime(time.localtime(time.time())) import calendarcalendar.month(2021 , 11 ) tss1 = '2018-10-10 23:40:00' timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S" ) timeStamp = int (time.mktime(timeArray)) tss2 = "2013-10-10 23:40:00" timeArray = time.strptime(tss2, "%Y-%m-%d %H:%M:%S" ) otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S" , timeArray) timeStamp = 1381419600 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S" , timeArray) timeStamp = 1381419600 dateArray = datetime.datetime.utcfromtimestamp(timeStamp) otherStyleTime = dateArray.strftime("%Y--%m--%d %H:%M:%S" ) now = int (time.time()) timeArray = time.localtime(now) otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S" , timeArray) now = datetime.datetime.now() otherStyleTime = now.strftime("%Y--%m--%d %H:%M:%S" )
configparser模块 通常用作配置文件的增删改查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 import configparserconf = configparser.ConfigParser() conf['mysql' ] = { 'user' : 'nihao' , 'passwd' : 123456 , 'port' : 3306 } conf['redis' ] = {} conf['redis' ]['user' ] = 'nihao' conf['redis' ]['passwd' ] = '123456' conf['redis' ]['port' ] = '6379' with open ('conf.txt' , 'w' ) as configfile: conf.write(configfile) import configparserconf = configparser.ConfigParser() conf.read('conf.txt' ) sec = conf.sections() opt = conf.options('mysql' ) item = conf.items('redis' ) v_int = conf.getint('redis' , 'passwd' ) v_boolean = conf.getboolean('redis' , 'tpye' ) v_float = conf.getfloat('redis' , 'salary' ) v_all = conf.get('redis' , 'all' ) import configparserconf = configparser.ConfigParser() conf.read('conf.txt' ) conf.add_section('db' ) conf.add_section('123' ) conf.remove_section('123' ) conf.set ('db' , 'db_username' , 'rainbol' ) conf.set ('db' , 'db_password' , '123456' ) conf.remove_option('mysql' , 'user' ) conf.remove_option('mysql' , 'passwd' ) conf.set ('mysql' , 'username' , 'root' ) conf.set ('mysql' , 'password' , '654321' ) conf.clear() conf.write(open ('conf.txt' , 'w' , encoding='utf-8' ))
itsdangerous模块 #一种的加密方式,程序解析加密和加密字符串,可以记录TTL和盐值
1 2 3 4 5 6 7 8 9 salt = 'saO)(&)H' t = itsdangerous.TimedJSONWebSignatureSerializer(salt, expires_in=600 ) res = t.dumps({'username' : 'rainbol' , 'password' : '123456' }) print (res.decode()) session = 'eyJhbGciOiJIUzUxMiIsImlhdCI6MTU0MjAwMTcwNCwiZXhwIjoxNTQyMDAyMzA0fQ.eyJ1c2VybmFtZSI6IkNoZW56dWFueWkxMjMiLCJwYXNzd29yZCI6IkN6eTEyMzQhISJ9tOdU5gNQdIVONPoD5DLxsW4lRcDX_n3Bg82RR5C48uXT5JhW7Z_UYqpZYd16p9tlT7moXM-T0Son07_KGaBJvA' res = t.loads(session) print (res)
glod模块 过滤目录
1 2 3 4 5 * ,?,[] * :匹配0 个或多个字符; ? :匹配单个字符; []:匹配指定范围内的字符
1 2 3 4 print (glob.glob('*.py' )) _list = glob.glob(BASEPATH + os.sep + '*' + os.sep + '/*.html' ) _list = glob.glob('../*.html' )
判断操作系统,如os,linux,windows
1 2 3 4 5 6 7 8 9 10 import platformimport osif platform.system().lower() == 'linux' : os.system('ls' ) elif platform.system().lower() == 'windows' : os.system('dir' ) else : pass
gevent模块 基于greenlet封装,避免多线程切换导致io执行效率降低
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import geventfrom gevent import monkeymonkey.patch_all() def run (name, url ): r = requests.get(url) open (name + '.html' , 'wb' ).write(r.content) url = {'rainbol01' : 'https://www.cnblogs.com/RainBol/' , 'rainbol02' : 'https://www.cnblogs.com/RainBol/p/9505438.html' , 'rainbol03' : 'https://www.cnblogs.com/RainBol/p/10077388.html' } for name, url in url.items(): g = gevent.spawn(run, name, url) g.join()
logger模板 logger模板[1]
#日志是一种可以追踪某些软件运行时所发生事件的方法。
python封装好了我们可以使用生成的日志报告框架
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 import logginglogging.basicConfig(level=logging.DEBUG, format ='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s' , datefmt='%a,%d %b %Y %H:%M:%S' , filename='test.log' , filemode='w' ) ''' %(name)s 打印日志名称 %(levelno)s 打印日志级别的数值 %(levelname)s 打印对应filename参数中的设置的log路径 %(pathname)s 打印当前执行程序的路径 %(filename)s 打印文件名 %(module)s 打印日志输出函数的模块名 %(lineno)d 记录执行代码行号 %(funcName)s 由哪个function发出的log, 调用日志输出函数的函数名 %(created)f 当前时间,用UNIX标准的表示时间的浮点数表示; 日志事件发生的时间--时间戳,就是当时调用time.time()函数返回的值 %(asctime)s 对应datefmt参数中设置的时间 %(msecs)d 日志事件发生事件的毫秒部分 %(relativeCreated)d 日志记录创建时的时间(以毫秒为单位),与加载日志模块的时间(通常在应用程序启动时)相关 %(thread)d 打印线程id %(threadName)s 打印线程名称 %(process)d 打印进程id %(message)s 打印日志信息 ''' logging.debug('this is debug message' ) logging.info('this is info message' ) logging.warning('this is warning message' ) logging.error('this is error message' ) logging.critical('this is critical message' )
logger模板 logger模板[2]
#既想输出屏幕还输出到文件用此格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import logginglogger = logging.getLogger() filer = logging.FileHandler('test.log' ) stream = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) filer.setFormatter(formatter) stream.setFormatter(formatter) logger.addHandler(filer) logger.addHandler(stream) logger.setLevel(logging.DEBUG) logger.debug('this is debug message' ) logger.info('this is info message' ) logger.warning('this is warning message' ) logger.error('this is error message' ) logger.critical('this is critical message' )
参考:https://www.cnblogs.com/Nicholas0707/p/9021672.html
hashlib模块 hashlib模块
1 2 3 4 5 6 7 import hashlibpassword1 = '123456' res = password1.encode() m = hashlib.md5(res) print (m.hexdigest())
加盐:
二级加密,保证数据的安全,我们会在md5加密代码前加上一个特定的字符串,
如123456helloworld,输入密码为123456,
进过加盐对123456helloworld进行md5加密,
当用户登录输入密码,代码自动在用户输入密码后加盐,转出md5与数据库匹配
除了MD5还有sha.224,sha256更安全,
由于md5算法是不可逆的,所以按照实际业务来实现算法
双重加密
加密两次,我们使用os.urandom(n)
#表示一个生成n个字节随机字符串,当然每次打印生成的结果肯定是不一样的uuid加密
1 2 3 4 import uuidres = uuid.uuid4()
1 2 3 4 5 6 7 import osfrom hashlib import md5req = os.urandom(24 ) res = md5(os.urandom(24 )).hexdigest() print (res)
importlib模块 importlib模块 #实现动态导入模块并执行
1 2 3 4 5 6 7 8 import importlibmode = 'libtest.importlib_test' fuc = 'run' moc = importlib.import_module(mode) res = getattr (moc, fuc) res()
heapq模块 heapq模块 #从一个集合中查找最大最小的N个元素——Python heapq 堆数据结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import heapqnum = [23 , 213 , 1 , 23 , 2 , 23 , 24 , 5 , 345 , 34.324 , 5 , 3 , 52 ] max = heapq.nlargest(3 , num) min = heapq.nsmallest(3 , num) portfolio = [ {'name' : 'IBM' , 'shares' : 100 , 'price' : 91.1 }, {'name' : 'AAPL' , 'shares' : 50 , 'price' : 543.22 }, {'name' : 'FB' , 'shares' : 200 , 'price' : 21.09 }, {'name' : 'HPQ' , 'shares' : 35 , 'price' : 31.75 }, {'name' : 'YHOO' , 'shares' : 45 , 'price' : 16.35 }, {'name' : 'ACME' , 'shares' : 75 , 'price' : 115.65 } ] print (heapq.nlargest(3 , portfolio, lambda x: x['shares' ]))
判断是否为函数 1 2 3 4 5 6 7 8 9 10 callable () def hanshu (): pass print (callable (hanshu)) print (callable ('我不是函数' ))
判断最小值 min()函数 判断最小
1 2 3 4 5 6 7 8 9 10 11 12 13 14 print(min('abc123')) print(min([2, 3, 4, 5, 6, 7, 1])) print(min({1: '213', 2: '42'})) print(min((2, 3, 4, 5, 6, 7, 8, 1))) print(min((({4: 'a', 2: 'b', 1: 'c'})))) # 不管里面有多少层 print(min({'a': '213', 'b': '42'})) # key参数 print(min({"username": "123", "password": "321"}, {"username": "342", "password": "5343"}, key=lambda x: x["username"])) # 多字典函数时指定函数区分 # default参数 print(min('', default='默认值')) # 空字符串,空列表,空元祖,空字段,可设返回默认值
第三方库 faker模块 不是打LoL的faker
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import fakerf2 = faker.Faker(locale='zh-CN' ) print (f2.ssn()) print (f2.phone_number()) print (f2.email()) print (f2.address()) print (f2.name()) print (f2.postcode())print (f2.street_address()) print (f2.street_name()) print (f2.street_suffix()) print (f2.street_address()) print (f2.date()) print (f2.ipv4()) print (f2.url()) print (f2.phone_number()) print (f2.simple_profile())
jsonpath模块 jsonpath模块
#方便取json的模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import jsonpathes = { "mappings" : { "article" : { "properties" : { "type" : "string" , "analyzer" : "english" } , "post_date" : { "type" : "date" }, "title" : { "type" : "string" }, "publiser_id" : { "type" : "long" } } } } result01 = jsonpath.jsonpath(es, 'mappings' ) result02 = jsonpath.jsonpath(es, 'article' ) result03 = jsonpath.jsonpath(es, '$..analyzer' ) print (result03)
参考原文:https://www.cnblogs.com/RainBol/p/9505438.html
QQ群:397745473