sys模块
1 import sys 2 3 sys.argv #命令行参数List,第一个元素是程序本身路径,答应当前的相对路径 4 sys.exit(n) #退出程序,正常退出时exit(0) 5 sys.version #获取Python解释程序的版本信息 6 sys.maxint #最大的Int值 7 sys.path #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 8 sys.platform #返回操作系统平台名称 9 sys.stdout.write('please:') #进度条演示 10 val = sys.stdin.readline()[:-1]
进度条
import sys import time for i in range(18): sys.stdout.write('#') sys.stdout.flush() time.sleep(0.15)
time&datetime模块
#-*-coding:utf-8 -*- ####################### time ####################### import time #属性 time.timezone #返回本地时间与标准时间之间的差,秒/s为单位 time.altzone #返回本地时间与夏令时时间之间的差,秒/s为单位 time.daylight #判断是否启用夏令时 #方法 time.time() #返回本地当前时间的时间戳 time.clock() ##返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来 time.sleep() #延迟几秒钟运行,秒/s为单位 time.gmtime(['seconds']) #返回utc时间的struce时间对象格式,参数为秒 time.localtime() #返回本地时间 的struce时间对象格式 time.asctime([tuple]) #返回时间格式"Fri Aug 19 11:14:16 2016",其参数为元组 time.ctime(['seconds']) #返回时间格式"Fri Aug 19 11:14:16 2016",其参数为时间戳(秒) time.mktime([tuple]) #将utc时间戳转换成struct_time格式,参数为元组 time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) #将utc struct_time格式转成指定的字符串格式 time.strptime('2017-07-22 17:57:42','%Y-%m-%d %H:%M:%S') #将 日期字符串 转成 struct时间对象格式 对应表: %a 本地(locale)简化星期名称 %A 本地完整星期名称 %b 本地简化月份名称 %B 本地完整月份名称 %c 本地相应的日期和时间表示 %d 一个月中的第几天(01 - 31) %H 一天中的第几个小时(24小时制,00 - 23) %I 第几个小时(12小时制,01 - 12) %j 一年中的第几天(001 - 366) %m 月份(01 - 12) %M 分钟数(00 - 59) %p 本地am或者pm的相应符 一 %S 秒(01 - 61) 二 %U 一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。 三 %w 一个星期中的第几天(0 - 6,0是星期天) 三 %W 和%U基本相同,不同的是%W以星期一为一个星期的开始。 %x 本地相应日期 %X 本地相应时间 %y 去掉世纪的年份(00 - 99) %Y 完整的年份 %Z 时区的名字(如果不存在为空字符) %% ‘%’字符 ####################### datetime ####################### import datetime print(datetime.datetime.now()) #获取当前时间,返回"2017-07-22 18:17:10.302974" print(datetime.date.fromtimestamp(time.time())) #将时间戳格式直接转换成"2017-07-22"格式 print(datetime.datetime.now() + datetime.timedelta(3)) # 当前时间+3天 print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天 print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时 print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 # c_time = datetime.datetime.now() # print(c_time.replace(minute=3,hour=2)) #时间替换
random模块
1 import random 2 3 random.seed(x) #给随机数一个种子,默认随机种子是系统时钟 4 random.random() #生成[0, 1.0)之间的随机小数 5 random.uniform(a, b) #生成一个a到b之间的随机小数 6 random.randint(a, b) #生成一个指定范围内的整数 7 random.randrange(a, b, c) #随机生成一个从a到b以c递增的数 8 random.choice() #从列表中随机返回一个元素 9 random.shuffle() #将列表中元素随机打乱 10 random.smple(list, k) #从指定列表中随机获取k个元素
四位随机验证码:
import random checkcode = '' for i in range(4): current = random.randint(0,4) #字母 if current == i: tmp = random.randint(0, 9) else: a_list = [] for a in range(65,91): a_list.append(chr(a)) for b in range(95,123): a_list.append(chr(b)) tmp = random.choice(a_list) checkcode += str(tmp) print(checkcode)
os模块
1 import os 2 3 os.getcwd() #获取当前工作目录,即当前python脚本工作的目录路径 4 os.chdir("dirname") #改变当前脚本工作目录;相当于shell下cd 5 os.curdir #返回当前目录: ('.') 6 os.pardir #获取当前目录的父目录字符串名:('..') 7 os.makedirs('dirname1/dirname2') #可生成多层递归目录 8 os.removedirs('dirname1') #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 9 os.mkdir('dirname') #生成单级目录;相当于shell中mkdir dirname 10 os.rmdir('dirname') #删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname 11 os.listdir('dirname') #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印 12 os.remove() #删除一个文件 13 os.rename("oldname","newname") #重命名文件/目录 14 os.stat('path/filename') #获取文件/目录信息 15 os.sep #输出操作系统特定的路径分隔符,win下为"\",Linux下为"/" 16 os.linesep #输出当前平台使用的行终止符,win下为" ",Linux下为" " 17 os.pathsep #输出用于分割文件路径的字符串 18 os.name #输出字符串指示当前使用平台。win->'nt'; Linux->'posix' 19 os.system("bash command") #运行shell命令,直接显示 20 os.environ #获取系统环境变量 21 os.path.abspath(path) #返回path规范化的绝对路径 22 os.path.split(path) #将path分割成目录和文件名二元组返回 23 os.path.dirname(path) #返回path的目录。其实就是os.path.split(path)的第一个元素返回path的目录。其实就是os.path.split(path)的第一个元素 24 os.path.basename(path) #返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素 25 os.path.exists(path) #如果path存在,返回True;如果path不存在,返回False 26 os.path.isabs(path) #如果path是绝对路径,返回True 27 os.path.isfile(path) #如果path是一个存在的文件,返回True。否则返回False 28 os.path.isdir(path) #如果path是一个存在的目录,则返回True。否则返回False 29 os.path.join(path1[, path2[, ...]]) #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 30 os.path.getatime(path) #返回path所指向的文件或者目录的最后存取时间 31 os.path.getmtime(path) #返回path所指向的文件或者目录的最后修改时间 32 33 cmd_red = os.system('dir') #调用接口传递给本地终端一个命令,只执行,但不保存 34 cmd_red = os.popen('dir').read() #调用接口传递给本地终端一个命令,执行并保存
更多戳这里:https://docs.python.org/2/library/os.html?highlight=os#module-os
shutil模块
高级的 文件、文件夹、压缩包 处理模块
1 import shutil 2 3 shutil.copyfileobj(fsrc, fdst[, length]) #将文件内容拷贝到另一个文件中,可以部分内容(需要手动打开两个文件) 4 shutil.copyfile(src, dst) #拷贝文件(无需手动打开文件,只需把文件名当作参数即可) 5 shutil.copymode(src, dst) #仅拷贝权限。内容、组、用户均不变 6 shutil.copystat(src, dst) #拷贝状态的信息,包括:mode bits, atime, mtime, flags 7 shutil.copy(src, dst) #拷贝文件和权限 8 shutil.copy2(src, dst) #拷贝文件和状态信息 9 shutil.copytree(src, dst, symlinks=False, ignore=None) #递归的去拷贝文件 10 shutil.rmtree(path[, ignore_errors[, onerror]]) #递归的去删除文件 11 shutil.move(src, dst) #递归的去移动文件 12 13 f = open('keys.txt','r') 14 f_n = open('key2.txt','w') 15 shutil.copystat('keys.text','key2.text') #拷贝状态的信息,包括:mode bits, atime, mtime, flags(文件需要存在)
ZipFile 和 TarFile模块
import zipfile # 压缩 z = zipfile.ZipFile('laxi.zip', 'w') z.write('a.log') z.write('data.data') z.close() # 解压 z = zipfile.ZipFile('laxi.zip', 'r') z.extractall() z.close() zipfile 压缩解压
import tarfile # 压缩 tar = tarfile.open('your.tar','w') tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip') tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip') tar.close() # 解压 tar = tarfile.open('your.tar','r') tar.extractall() # 可设置解压地址 tar.close() tarfile 压缩解压
import tarfile # 压缩 tar = tarfile.open('your.tar','w') tar.add('/Users/wupeiqi/PycharmProjects
json & pickle 模块
""" 用于序列化的两个模块 json,用于字符串 和 python数据类型间进行转换 pickle,用于python特有的类型 和 python的数据类型间进行转换 Json模块提供了四个功能:dumps、dump、loads、load pickle模块提供了四个功能:dumps、dump、loads、load """ ################ pickle ################ import pickle data = {'k1':123,'k2':'Hello'} #pickle.dumps 将数据通过特殊的形式转换为只有python语言认识的字符串,(序列化) p_str = pickle.dumps(data) print(p_str) #pickle.dump 将数据通过特殊的形式转换为只有python语言认识的字符串,并写入文件,(序列化) with open('result.pk','w') as fp: pickle.dump(data,fp) #packle.load 将数据从序列化文件中读取出来,(反序列化) f = open('result.pk','r') for line in f: print(pickle.loads(line)) ################ josn ################ import json #json.dumps 将数据通过特殊的形式转换为所有程序都认识的字符串,(序列化) j_str = json.dumps(data) print(j_str) #json.dump 将数据通过特殊的形式转换为只有python语言认识的字符串,并写入文件,(序列化) with open('result.json','w') as fp: json.dump(data,fp) #json.load 将数据从序列化文件中读取出来,(反序列化) f = open('result.json','r') for line in f: print(json.loads(line))
shelve 模块
#shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式 import shelve #序列化 import datetime d = shelve.open('shelve_test') # 打开一个文件 info = {'age':22,"job":'it'} name = ["lilk", "rain", "test"] d["name"] = name # 持久化列表 d["info"] = info # 持久dict d['date'] = datetime.datetime.now() d.close() #反序列化 d = shelve.open('shelve_test') # 打开一个文件 print(d.get("name")) print(d.get("info")) print(d.get("date"))
hashlib模块
用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。
import hashlib import hashlib m.digest() # 2进制格式hash m.hexdigest() # 16进制格式hash # ######## md5 ######## hash = hashlib.md5() hash.update('admin') print(hash.hexdigest()) # ######## sha1 ######## hash = hashlib.sha1() hash.update('admin') print(hash.hexdigest()) # ######## sha256 ######## hash = hashlib.sha256() hash.update('admin') print(hash.hexdigest()) # ######## sha384 ######## hash = hashlib.sha384() hash.update('admin') print(hash.hexdigest()) # ######## sha512 ######## hash = hashlib.sha512() hash.update('admin') print(hash.hexdigest())
xml处理模块
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单
xml创建:
import xml.etree.ElementTree as ET new_xml = ET.Element("namelist") name = ET.SubElement(new_xml, "name", attrib = {"enrolled": "yes"}) age = ET.SubElement(name, "age", attrib = {"checked": "no"}) sex = ET.SubElement(name, "sex") sex.text = '33' name2 = ET.SubElement(new_xml, "name", attrib = {"enrolled": "no"}) age = ET.SubElement(name2, "age") age.text = '19' et = ET.ElementTree(new_xml) # 生成文档对象 et.write("test.xml", encoding = "utf-8", xml_declaration = True) #写如xml文件 ET.dump(new_xml) # 打印生成的格式 输出内容: <namelist> <name enrolled="yes"> <age checked="no" /> <sex>33</sex> </name> <name enrolled="no"> <age>19</age> </name> </namelist>
XML
<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> </data>
修改与删除:
import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() # 修改 for node in root.iter('year'): new_year = int(node.text) + 1 node.text = str(new_year) node.set("updated", "yes") tree.write("xmltest.xml") #写入到原文件 # 删除node for country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country) tree.write('output.xml') #写入到新文件
处理:
import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() print(root.tag) # 遍历xml文档 for child in root: print(child.tag, child.attrib) for i in child: print(i.tag, i.text) # 只遍历year 节点 for node in root.iter('year'): print(node.tag, node.text)
ConfigParser模块
用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
创建配置文件:
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {} config['bitbucket.org']['User'] = 'hg' config['topsecret.server.com'] = {} # topsecret = config['topsecret.server.com'] topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' with open('setting.conf', 'w') as configfile: config.write(configfile) 生成的文件内容: [DEFAULT] compression = yes compressionlevel = 9 serveraliveinterval = 45 forwardx11 = yes [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no
读取配置文件内容:
import configparser conf = configparser.ConfigParser() conf.read("setting.conf") secs = conf.sections() #获取除默认区段外的所有区段的名称 print(secs) options = conf.options('topsecret.server.com') #获取指定区段中配置项的名称和默认区段中配置项的名称 print(options) item_list = conf.items('topsecret.server.com') #获取指定区段中配置项的名称和值 和 默认区段中配置项的名称和值 print(item_list) val = conf.get('topsecret.server.com','forwardx11') #获取指定区段,指定配置项的值 val = conf.getint('topsecret.server.com','host port') #获取指定区段,指定配置项的值(只能获取int类型)
修改配置文件:
import configparser config = configparser.ConfigParser() config.read('setting.conf') sec = config.remove_section('bitbucket.org') #删除一个配置段 config.write(open('setting.conf', "w")) sec = config.has_section('bitbet.org') #判断配置区段是否存在 print(sec) sec = config.add_section('test') #添加配置区段 config.write(open('setting.conf', "w")) config.set('bitbucket.org','user',"zhangsan") #修改区段中配置选项的值,添加区段的配置选项 config.write(open('seet.conf', "w")) config.remove_option('bitbucket.org','user') #删除区段的配置选项 config.write(open('seet.conf', "w"))