内置模块
一、os
用于提供系统级别的操作
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
os.curdir 返回当前目录: ('.')
os.pardir 获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2') 可生成多层递归目录
os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.stat('path/filename') 获取文件/目录信息
os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"os.pathsep 输出用于分割文件路径的字符串
os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'os.system("bash command") 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
二、sys
用于提供对解释器相关的操作
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0)
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的Int值
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
sys.stdout.write('please:')
val= sys.stdin.readline()[:-1]
三、hashlib
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
importhashlib######### md5 ########
hash=hashlib.md5()
hash.update('admin')printhash.hexdigest()######### sha1 ########
hash=hashlib.sha1()
hash.update('admin')printhash.hexdigest()######### sha256 ########
hash=hashlib.sha256()
hash.update('admin')printhash.hexdigest()######### sha384 ########
hash=hashlib.sha384()
hash.update('admin')printhash.hexdigest()######### sha512 ########
hash=hashlib.sha512()
hash.update('admin')print hash.hexdigest()
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
importhashlib######### md5 ########
hash= hashlib.md5('898oaFs09f')
hash.update('admin')print hash.hexdigest()
python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密
importhmac
h= hmac.new('wueiqi')
h.update('hellowo')print h.hexdigest()
四、json 和 pickle
用于序列化的两个模块
json,用于字符串 和 python数据类型间进行转换
pickle,用于python特有的类型 和 python的数据类型间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
五、ConfigParser
用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。
# 注释1
; 注释2
[section1]
k1 = v1
k2:v2
[section2]
k1 = v1
importConfigParser
config=ConfigParser.ConfigParser()
config.read('i.cfg')########### 读 ###########secs = config.sections()#print secs#options = config.options('group2')#print options
#item_list = config.items('group2')#print item_list
#val = config.get('group1','key')#val = config.getint('group1','key')
########### 改写 ###########sec = config.remove_section('group1')#config.write(open('i.cfg', "w"))
#sec = config.has_section('wupeiqi')#sec = config.add_section('wupeiqi')#config.write(open('i.cfg', "w"))
#config.set('group2','k1',11111)#config.write(open('i.cfg', "w"))
#config.remove_option('group2','age')#config.write(open('i.cfg', "w"))
六、logging
用于便捷记录日志且线程安全的模块
importlogging
logging.basicConfig(filename='log.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')
对于等级:
CRITICAL= 50FATAL=CRITICAL
ERROR= 40WARNING= 30WARN=WARNING
INFO= 20DEBUG= 10NOTSET= 0
七、time
时间相关的操作,时间有三种表示方式:
时间戳 1970年1月1日之后的秒,即:time.time()
格式化的字符串 2014-11-11 11:11, 即:time.strftime('%Y-%m-%d')
结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime()
printtime.time()printtime.mktime(time.localtime())print time.gmtime() #可加时间戳参数
print time.localtime() #可加时间戳参数
print time.strptime('2014-11-11', '%Y-%m-%d')print time.strftime('%Y-%m-%d') #默认当前时间
print time.strftime('%Y-%m-%d',time.localtime()) #默认当前时间
printtime.asctime()printtime.asctime(time.localtime())printtime.ctime(time.time())importdatetime'''datetime.date:表示日期的类。常用的属性有year, month, day
datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond
datetime.datetime:表示日期时间
datetime.timedelta:表示时间间隔,即两个时间点之间的长度
timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
strftime("%Y-%m-%d")'''
importdatetimeprintdatetime.datetime.now()print datetime.datetime.now() - datetime.timedelta(days=5)
八、random
随机数
mport randomprintrandom.random()print random.randint(1,2)print random.randrange(1,10)
随机验证码实例:
importrandom
checkcode= ''
for i in range(4):
current= random.randrange(0,4)if current !=i:
temp= chr(random.randint(65,90))else:
temp= random.randint(0,9)
checkcode+=str(temp)print checkcode