Python 常用模块使用
1、shelve模块 【内容持久化】
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # /usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import shelve 4 ''' 5 import shelve 6 d = shelve.open(filename) # open, with (g)dbm filename -- no suffix 7 d[key] = data # store data at key (overwrites old data if 8 # using an existing key) 9 data = d[key] # retrieve a COPY of the data at key (raise 10 # KeyError if no such key) -- NOTE that this 11 # access returns a *copy* of the entry! 12 del d[key] # delete data stored at key (raises KeyError 13 # if no such key) 14 flag = key in d # true if the key exists 15 list = d.keys() # a list of all existing keys (slow!) 16 d.close() # close it 17 18 functions: 19 'cache', 'clear', 'close', 'dict', 'get', 'items', 'keyencoding', 'keys', 20 'pop', 'popitem', 'setdefault', 'sync', 'update', 'values', 'writeback' 21 ''' 22 # shelve 数据写入(内容持久化),写入文件中的数据为乱码 23 d = shelve.open('shelve.db') 24 d['name'] = 'zws' 25 d['age'] = 23 26 d['weight'] = 130 27 d['dict'] = {'module': 'shelve', 'functions': 'cache...'} 28 d['list'] = ['name','age'] 29 d.close() 30 31 # shelve 数据读取 32 r = shelve.open('shelve.db') 33 # del r['weight'] #删除weight 34 # r.pop('name') #弹出‘name’ 35 # r.clear() #清空shelve.db文件内容 36 # myName = r.get('name') #获取key对应的值 37 # items = r.items() #获取r中的items 38 39 keys = r.keys() 40 for i in keys: 41 print("%s : %s" %(i,r[i])) 42 r.close()
2、time模块
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# /usr.bin/env python # -*- coding:utf-8 -*- import time ''' time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float gmtime() -- convert seconds since Epoch to UTC tuple localtime() -- convert seconds since Epoch to local time tuple asctime() -- convert time tuple to string ctime() -- convert time in seconds to string mktime() -- convert local time tuple to seconds since Epoch strftime() -- convert time tuple to string according to format specification strptime() -- parse string to time tuple according to format specification tzset() -- change the local timezone ''' # seconds ===> time.struct_time,默认为UTC时间 print(time.gmtime(time.time())) #time.struct_time(tm_year=2017, tm_mon=6, tm_mday=5, tm_hour=9, tm_min=20, tm_sec=23, tm_wday=0, tm_yday=156, tm_isdst=0) # time.struct_time ==> seconds print(time.mktime(time.gmtime())) #1496625623.0 # 字符串化时间格式 # time.struct_time ==> string,默认为当前时间 print(time.asctime(time.localtime())) # Mon Jun 5 17:20:23 2017 # seconds ==> string,默认为当前时间 print(time.ctime(time.time())) # Mon Jun 5 17:20:23 2017 #时间格式化 # time.struct_time ====> 格式化时间 print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) # 2017-06-05 17:20:23 # 格式化时间 ====> time.struct_time print(time.strptime('2017-06-05 17:15:25',"%Y-%m-%d %H:%M:%S")) #time.struct_time(tm_year=2017, tm_mon=6, tm_mday=5, tm_hour=17, tm_min=15, tm_sec=25, tm_wday=0, tm_yday=156, tm_isdst=-1) #获取当前时间 #time.struct_time,默认为当前时间 print(time.localtime()) # time.struct_time(tm_year=2017, tm_mon=6, tm_mday=5, tm_hour=17, tm_min=20, tm_sec=23, tm_wday=0, tm_yday=156, tm_isdst=0)
3、datetime模块
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # /usr.bin/env python 2 # -*- coding:utf-8 -*- 3 import datetime 4 import time 5 6 print(datetime.datetime.now()) #以格式化返回当前时间 7 print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2017-06-05 8 print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天 9 print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天 10 print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时 11 print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 12 13 c_time = datetime.datetime.now() 14 print(c_time.replace(minute=3,hour=2)) #时间替换 15 16 ''' 17 执行结果: 18 2017-06-05 18:54:42.663799 19 2017-06-05 20 2017-06-08 18:54:42.663943 21 2017-06-02 18:54:42.664008 22 2017-06-05 21:54:42.664020 23 2017-06-05 19:24:42.664032 24 2017-06-05 02:03:42.664044 25 '''
4、os模块
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 2 os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd 3 os.curdir 返回当前目录: ('.') 4 os.pardir 获取当前目录的父目录字符串名:('..') 5 os.makedirs('dirname1/dirname2') 可生成多层递归目录 6 os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 7 os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname 8 os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname 9 os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印 10 os.remove() 删除一个文件 11 os.rename("oldname","newname") 重命名文件/目录 12 os.stat('path/filename') 获取文件/目录信息 13 os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/" 14 os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n" 15 os.pathsep 输出用于分割文件路径的字符串 16 os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix' 17 os.system("bash command") 运行shell命令,直接显示 18 os.environ 获取系统环境变量 19 os.path.abspath(path) 返回path规范化的绝对路径 20 os.path.split(path) 将path分割成目录和文件名二元组返回 21 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 22 os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 23 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False 24 os.path.isabs(path) 如果path是绝对路径,返回True 25 os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False 26 os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False 27 os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 28 os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间 29 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间