zoukankan      html  css  js  c++  java
  • python基础-------模块

    在python中,只有函数,类,模块能开辟出作用域,for循环跟while循环,还有if语句是不能开辟作用域的

    模块:模块就是.py文件

    1,时间模块:time模块

     1 import time
     2 #1时间戳:是一个float类型
     3 print(time.time())  #从1970年1月1日0点0分,到目前走了多少秒
     4 #1493189111.495058
     5 
     6 #2格式化时间字符串: 给人看的
     7 print(time.strftime("%Y-%m-%d %X")) #%Y是年,%m是月,%d是日,%X对应的此时此刻的时间
     8 #2017-04-26 14:47:18
     9 
    10 #3结构化时间:是用来对时间操作的
    11 print(time.localtime())
    12 #time.struct_time(tm_year=2017, tm_mon=4, tm_mday=26,
    13 #tm_hour=14, tm_min=49, tm_sec=20, tm_wday=2, tm_yday=116, tm_isdst=0)

    1.2 几种时间的格式转换

    1 #时间戳----》结构化时间
    2 print(time.localtime(3600*24))
    3 #结构化时间----》时间戳
    4 print(time.mktime(time.localtime()))#1493190476.0
    5 #字符串时间---》结构化时间
    6 print(time.strftime("%Y-%m-%d %X",time.localtime()))
    7 
    8 time.sleep(1)#程序睡眠1秒在执行

    注意:字符串时间跟时间戳是不能相互转换的

    2,随机数模块:random模块

     1 #随机数模块 random
     2 import random
     3 
     4 #大于0且小于1之间的小数,随机取
     5 print(random.random())  #0.30622226383048434
     6 
     7 #随机取大于等于1且小于10之间的整数
     8 print(random.randrange(1,10))
     9 
    10 #随机取列表内的
    11 print(random.choice([1,"hello",[1,2,3,4]])) #hello
    12 #随机取列表内的下个元素
    13 print(random.sample([1,2,3,4,5,6],2)) #[4, 2]
    14 
    15 #随机取大于1小于4的小数
    16 print(random.uniform(1,4)) #1.5512894269017037
    17 
    18 #打乱顺序
    19 item = [1,2,3,4,5,6,7,8,10,9]
    20 random.shuffle(item)
    21 print(item) #[6, 4, 7, 9, 3, 2, 5, 10, 1, 8]

    2.1,随机生成5位的字母+数字验证码

     1 #生成验证码,   五位数的字母数字组合
     2 import random
     3 def number():
     4     s = ""
     5     for i in range(5):
     6         num = str(random.randint(0,9))     #随机取0-9中的任意一个数字
     7         str1 = str(chr(random.randint(65,90)))  #把65-90之间的数字转成对应ascll大写字母
     8         str2 = str(chr(random.randint(97,122))) #把97-122之间的数字随机取出来一个转成对应的ascll小写英文字母
     9         msg = random.choice([num,str1,str2])     #
    10         s+=msg
    11 
    12     return s
    13 
    14 print(number()) #6BZ2z

    3,摘要算法:hashlib模块

    摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)。

    有md5,sha1,sha3_224 等等

     1 import hashlib
     2 #md5摘要算法
     3 a = hashlib.md5()  #32位16进制字符串表示
     4 a.update("hello".encode("utf-8"))
     5 print(a.hexdigest())
     6 
     7 #md5执行结果:5d41402abc4b2a76b9719d911017c592
     8 
     9 #sha1摘要算法
    10 b = hashlib.sha1()   #40位16进制字符串表示
    11 b.update("hello".encode("utf-8"))
    12 print(b.hexdigest())
    13 #
    14 #sha1执行结果:aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
    15 
    16 
    17 #sha3_224摘要算法
    18 c  =hashlib.sha3_224()  #56位16进制字符串表示
    19 c.update("hello".encode("utf-8"))
    20 print(c.hexdigest())
    21 
    22 #sha3__224执行结果:b87f88c72702fff1748e58b87e9141a42c0dbedc29a78cb0d4a5cd81

    3.1我们以一个常见的md5算法计算:

    1 a1 = hashlib.md5()
    2 a1.update("hello wold hello python hello gaoyuan".encode("utf-8"))
    3 print(a1.hexdigest())
    4 
    5 #计算结果:954385d49876e770b48038cbae52f33e

      3.2 如果数据量很大,可以分块多次调用update(),最后计算的结果是一样的:

    1 a1 = hashlib.md5()
    2 a1.update("hello wold ".encode("utf-8"))
    3 a1.update("hello python ".encode("utf-8"))
    4 a1.update("hello gaoyuan".encode("utf-8"))
    5 
    6 print(a1.hexdigest())
    7 
    8 #计算结果:954385d49876e770b48038cbae52f33e
    9 #跟上面例子的结果是一模一样的,千万要注意空格,有空格跟没空格完全是两个结果

    3.3越长的摘要算法越安全,但是相对的计算时间长

    3.4由于常用口令的MD5值很容易被计算出来,所以,要确保存储的用户口令不是那些已经被计算出来的常用口令的MD5,这一方法通过对原始口令加一个复杂字符串来实现,俗称“加盐”:

     1 #普通算法:
     2 obj = hashlib.md5()
     3 obj.update("123456".encode("utf-8"))
     4 print(obj.hexdigest())
     5 
     6 # 123456经过MD5计算结果是:e10adc3949ba59abbe56e057f20f883e
     7 
     8 obj = hashlib.md5("salt".encode("utf-8")) #加盐算法
     9 obj.update("123456".encode("utf-8"))
    10 print(obj.hexdigest())
    11 
    12 # 经过加盐算法计算结果是:f51703256a38e6bab3d9410a070c32ea

    经过Salt处理的MD5口令,只要Salt不被黑客知道,即使用户输入简单口令,也很难通过MD5反推明文口令。

    但是如果有两个用户都使用了相同的简单口令比如123456,在数据库中,将存储两条相同的MD5值,这说明这两个用户的口令是一样的。有没有办法让使用相同口令的用户存储不同的MD5呢?

    如果假定用户无法修改登录名,就可以通过把登录名作为Salt的一部分来计算MD5,从而实现相同口令的用户也存储不同的MD5。

    摘要算法在很多地方都有广泛的应用。要注意摘要算法不是加密算法,不能用于加密(因为无法通过摘要反推明文),只能用于防篡改,但是它的单向计算特性决定了可以在不存储明文口令的情况下验证用户口令。

    4,os模块: os模块是与操作系统交互的一个接口

     1 '''
     2 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
     3 os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
     4 os.curdir  返回当前目录: ('.')
     5 os.pardir  获取当前目录的父目录字符串名:('..')
     6 os.makedirs('dirname1/dirname2')    可生成多层递归目录
     7 os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
     8 os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
     9 os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
    10 os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    11 os.remove()  删除一个文件
    12 os.rename("oldname","newname")  重命名文件/目录
    13 os.stat('path/filename')  获取文件/目录信息
    14 os.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
    15 os.linesep    输出当前平台使用的行终止符,win下为"	
    ",Linux下为"
    "
    16 os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
    17 os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
    18 os.system("bash command")  运行shell命令,直接显示
    19 os.environ  获取系统环境变量
    20 os.path.abspath(path)  返回path规范化的绝对路径
    21 os.path.split(path)  将path分割成目录和文件名二元组返回
    22 os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
    23 os.path.basename(path)  返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
    24 os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
    25 os.path.isabs(path)  如果path是绝对路径,返回True
    26 os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
    27 os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
    28 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
    29 os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
    30 os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
    31 os.path.getsize(path) 返回path的大小
    32 '''

    五,sys模块

    1 sys.argv           命令行参数List,第一个元素是程序本身路径
    2 sys.exit(n)        退出程序,正常退出时exit(0)
    3 sys.version        获取Python解释程序的版本信息
    4 sys.maxint         最大的Int值
    5 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    6 sys.platform       返回操作系统平台名称

     六,作业1:

    1 小程序:根据用户输入选择可以完成以下功能:
    创意文件,如果路径不存在,创建文件夹后再创建文件
    能够查看当前路径
    在当前目录及其所有子目录下查找文件名包含指定字符串的文件

     1 import os,time
     2 class File:
     3 
     4     def create(self):
     5         while True:
     6             choice = input("please input file_path:
    ").strip()
     7             file_path = os.path.split(choice)
     8             choice1 = file_path[0]
     9             if os.path.isdir(choice1):
    10                 print("Your content has been written to the file")
    11                 continue
    12             os.makedirs(choice1)
    13             f = open(choice,"w",encoding="utf-8")
    14             f_write = input("please your input content:").strip()
    15             f.write(time.strftime("%Y-%m-%d %X")+"	"+f_write)
    16             print("The current file path is")
    17             f.close()
    18             break
    19 
    20     def look_path(self):
    21         print("The current file path is".center(50,"-"))
    22         print(os.getcwd()+"
    ")
    23 
    24     def look_contents(self):
    25         print("This is the current directory of all the files directory".center(100,"-"))
    26         file = os.getcwd()
    27         data = os.listdir(file)
    28         for i in data:
    29             if str(i):
    30                 print(i)
    31 f = File()
    32 
    33 def main():
    34     msg = {"1":"create_file",
    35            "2":"look_path",
    36            "3":"look_contents",
    37            "4":"quit"
    38            }
    39 
    40     while True:
    41         for key, value in msg.items():
    42             print(key, value+"")
    43 
    44         choice = input("pleale your input serial number :
    ")
    45         for key in msg:
    46             if not msg[key]:continue
    47         if choice == "1":
    48             f.create()
    49         if choice == "2":
    50             f.look_path()
    51         if choice == "3":
    52             f.look_contents()
    53         else:
    54             if choice == "4":
    55                 print("当前时间 : %s" %(time.strftime("%Y-%m-%d %X")))
    56                 print("bye bye".center(50,"-"))
    57                 exit()
    58 
    59 
    60 if __name__ == '__main__':
    61     main()

    作业四:显示当前时间三天后是星期几?

    #4 显示当前时间三天后是星期几?
    import time
    print(time.ctime())
    print(time.ctime(1493216339+3600*24*3))
    #当前时间:Wed Apr 26 22:18:03 2017
    #三天后: Sat Apr 29 22:20:59 2017
  • 相关阅读:
    linux curses函数库
    在Android library中不能使用switch-case语句访问资源ID的原因分析及解决方案
    Android Support ;v4、v7、v13的区别
    background-position
    java web 之 web.xml篇
    javaweb之Cookie篇
    Enumeration 接口
    Java Bad version number in .class file
    使用AppCan自带的升级功能实现移动端升级
    obj.offsetHeight与obj.style.height区别
  • 原文地址:https://www.cnblogs.com/gaoyuan111/p/6769771.html
Copyright © 2011-2022 走看看