python学习——常用模块

  • random模块
  • time模块
  • sys模块
  • os模块
取随机数的模块
import random

#去随机小数:数学计算
import random
print(random.random()) #去0~1之间
print(random.uniform(1,2)) # 去范围内的小数
#去随机整数
# 应用:彩票,抽奖
import random
print
(random.randint(1,2)) #[1,2]顾头也顾尾 print(random.randrange(1,2)) # [1,2)顾头不顾尾 print(random.randrange(1,200,2)) #随机冲去200内的
#从一个列表中随机抽取值
# 应用:抽奖
import random
l = ['a','b',(1,2),123]
print(random.choice(l))
print(random.sample(l,2)) # 连续抽取两次,不重复
#打乱一个列表的顺序,在原列表直接进行修改,节省空间
# 应用:洗牌
import random
random.shuffle(l)
print(l)
#验证码
#4位整数验证码
#6位数字验证码
#6位数字+字母验证码

#数字验证码
import random
#while 循环
s = ''
while len(s)<4:
    num = str(random.randint(0, 9))
    s = s +num
print(s)
#for循环
s = ''
for i in range(4):
    num = random.randint(0,9)
    s = s + str(num)
print(s)
#数字验证码函数版本
import random
def code(n=6):
    s = ''
    while len(s) < n:
        num = str(random.randint(0, 9))
        s = s + num
    return s
print(code(4))
print(code(6))
#数字+字母
import random
def code(n):
    s = ''
    for i in range(n):
        num = random.randint(0,9)
        alpha_upper = chr(random.randint(65,90))
        alpha_lower = chr(random.randint(97,122))
        res = random.choice([num,alpha_upper,alpha_lower])
        s = s +str(res)
    return s
print(code(6))
#数字,字母可控
import random
def code(n,alpha=True):
    s = ''
    for i in range(n):
        num = str(random.randint(0,9))
        if alpha:
            alpha_upper = chr(random.randint(65,90))
            alpha_lower = chr(random.randint(97,122))
            num = random.choice([num,alpha_upper,alpha_lower])
        s = s +num
    return s
print(code(6,True))
 
# time模块主要是用来和时间打交道的
# 时间格式
#'2018-08-20' 字符串数据类型 格式化-给人看的
#结构化时间
#1565748617.8853261 浮点型数据类型,以s为单位 时间戳时间-给机器计算用的
#1970 1 1 0:0:0伦敦时间到此时
time.sleep(2) # 程序走这会等待2两秒钟
#时间戳时间
print(time.time())
#格式化时间
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 格式化时间
print(time.strftime('%y-%m-%d %H:%M:%S')) # 格式化时间
print(time.strftime('%c')) # 格式化时间
#结构化时间
struct_time = time.localtime() # 北京时间
print(struct_time) # 北京时间
print(struct_time.tm_year)
#时间戳--》字符串时间
print(time.time())
strucy_time = time.localtime(150000000)
ret = time.strftime('%y/%m/%d %H:%M:%S',strucy_time)
print(ret)
#字符串时间-->时间戳
strucz_time = time.strptime('2018-8-8','%Y-%m-%d')
print(strucz_time)
res = time.mktime(strucz_time)
print(res)
#查看一下2000000000时间戳时间表示的年月日
strucy_time = time.localtime(2000000000)
ret = time.strftime('%Y/%m/%d %H:%M:%S',strucy_time)
print(ret)
#将2008-8-8转换成时间戳时间
t = time.strptime('2008-8-8','%Y-%m-%d')
print(t)
print(time.mktime(t))
#请将当前时间的当前月1号的时间戳时间取出来
st = time.localtime()
st2 = time.strptime('%s-%s-1'%(st.tm_year,st.tm_mon),'%Y-%m-%d')
print(time.mktime(st2))
#计算时间差
#2018-8-19 22:10:8 2018-8-20 11:07:3
#经过了多少时分秒
str_time1 = '2018-8-19 22:10:8'
str_time2 = '2018-8-20 11:07:3'
struct_t1 = time.strptime(str_time1,'%Y-%m-%d %H:%M:%S')
struct_t2 = time.strptime(str_time2,'%Y-%m-%d %H:%M:%S')
timestamp1 = time.mktime(struct_t1)
timestamp2 = time.mktime(struct_t2)
sub_time = timestamp2 - timestamp1
gm_time = time.gmtime(sub_time)
print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(gm_time.tm_year-1970,gm_time.tm_mon-1,
                                       gm_time.tm_mday-1,gm_time.tm_hour,
                                       gm_time.tm_min,gm_time.tm_sec))

sys模块

 sys模块是与python解释器交互的一个接口

  sys.argv 命令行参数List,第一个元素是程序本身路径

  sys.exit(n) 退出程序,正常退出时exit(0),错误退出sys.exit(1)

  sys.version 获取Python解释程序的版本信息

  sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

  sys.platform 返回操作系统平台名称

os模块

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.system("bash command")  运行shell命令,直接显示
os.popen("bash command).read()  运行shell命令,获取执行结果
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd


os.path
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所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小

注意:os.stat('path/filename' 获取文件/目录信息 的结构说明

stat 结构:

st_mode: inode 保护模式
st_ino: inode 节点号。
st_dev: inode 驻留的设备。
st_nlink: inode 的链接数。
st_uid: 所有者的用户ID。
st_gid: 所有者的组ID。
st_size: 普通文件以字节为单位的大小;包含等待某些特殊文件的数据。
st_atime: 上次访问的时间。
st_mtime: 最后一次修改的时间。
st_ctime: 由操作系统报告的"ctime"。在某些系统上(如Unix)是最新的元数据更改的时间,在其它系统上(如Windows)是创建时间(详细信息参见平台的文档)。

stat 结构
os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep    输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'

猜你喜欢

转载自www.cnblogs.com/bilx/p/11351489.html