江湖道

庙堂,江湖,学术!

返回顶部

python之模块分类(一)

模块的分类

(1)标准库(内置模块)

python自带的模块,例如:time,datetime

python中常用的时间的表示方式:格式化后的字符串,时间戳,元组

#Author:Anliu
import time,datetime
print(time.time())   #获取时间戳
print(time.localtime())  #本地时间 UTC+8,元组的形式呈现
time.sleep(2)      #程序停2秒
print(time.gmtime())   #UTC时间,元组的形式呈现
print(time.gmtime(time.time()))

x=time.gmtime()
print(x)
print(x.tm_year)
print(x.tm_mon)
print(x.tm_mday)
print(time.mktime(x))   #元组转化为时间戳

print(time.strftime("%Y-%m-%d %H:%M:%S",x))   #元组转化为格式化的字符串
print(time.strptime("2019-11-08 01:52:03","%Y-%m-%d %H:%M:%S"))  #格式化的字符串转化成元组
print(time.asctime())  #元组转换成字符串格式
print(time.ctime())   #时间戳转换成字符串格式
print(datetime.datetime.now())  #打印当前时间
print(datetime.datetime.now() + datetime.timedelta(3))  #当前时间的后3天
print(datetime.datetime.now() + datetime.timedelta(-3))  #当前时间的前3天
print(datetime.datetime.now() + datetime.timedelta(hours=8))
print(datetime.datetime.now() + datetime.timedelta(hours=-8))

 random模块

#Author:Anliu
import random
print(random.random())  #随机浮点数
print(random.randint(1,3)) #打印1,3的随机整数
print(random.randrange(1,3))  #打印1,2的随机整数
print(random.choice('hello'))   #字符串列表或者元素
print(random.sample('hello',2))   #随机取两个字符
list=["a","b","c","d","e","f","g"]
random.shuffle(list)    #打乱列表顺序
print(list)

random实例:验证码

#Author:Anliu
import random
#打印四位数字
#checkcode=''
#for i in range(4):
#    current=random.randint(1,9)
#    checkcode+=str(current)
#print(checkcode)

#打印四位数字加字母
checkcode=''
for i in range(4):
    current=random.randrange(0,4)
    if current == i:
        tmp = chr(random.randint(65,90))
    else:
        tmp = random.randint(0,9)
    checkcode+=str(tmp)
print(checkcode)

 os模块

#Auth: Anliu                                                                       
import os,time                                                                     
#print(os.getcwd())                                                                
#os.chdir("/home")                                                                 
#print(os.getcwd())                                                                
#print(os.curdir)                                                                  
#print(os.getcwd())                                                                
#print(os.pardir)                                                                  
#print(os.getcwd())                                                                
#os.makedirs(r"/test/test/123/111")                                                
#os.removedirs(r"/test/test/123/111")                                              
#os.mkdir(r"/test")                                                                
#os.rmdir(r"")                                                                     
#print(os.listdir('.'))                                                            
##os.rename("test.py","123.py")                                                    
#print(os.stat('123.py'))                                                          
#print(os.sep)                                                                     
#print(os.linesep)                                                                 
#print(os.pathsep)                                                                 
#print(os.environ)                                                                 
#print(os.name)                                                                    
#print(os.system("pwd"))                                                           
#print(os.path.abspath("123.py"))                                                  
#print(os.path.split("/home/123"))                                                 
print(os.path.dirname("/home/123.py"))                                             
print(os.path.basename("/home/123.py"))                                            
print(os.path.exists("/test"))                                                     
print(os.path.isabs("/home"))                                                      
print(os.path.isfile("123.py"))                                                    
print(os.path.isdir("/home"))                                                      
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime(os.path.getatime("123.py"))))  
print(os.path.getmtime("123.py"))                                                  

 sys模块

#Author:Anliu
import sys
#(1)sys.argv
#print(sys.argv)  #打印文件名以及参数
#a = sys.argv[0]  #传递位置参数
#b = sys.argv[1]
#print(a,b)

#(2)sys.exit(1)  退出程序机制
#通过引发SystemExit异常来退出Python程序。
#可以通过捕捉SystemExit异常,在finally语句中进行一些清理操作;不捕捉SystemExit异常(SystemExit异常不被认为是错误的异常)将直接退出程序。
#退出程序,正常退出为sys.exit(0)

#不捕捉SystemExit异常,直接退出程序:
#Author:Anliu
import sys,time

print("Type exit to exit.")
while True:
    response = input(">>>")
    if response.upper() == "EXIT":
        print("you have typed exit ,and system will exit right now...")
        time.sleep(0.1)
        sys.exit()
    print("you typed" + response + '.')

#捕捉SystemExit异常,可以做一些工作,如打印异常消息等:
#Author:Anliu
import sys

def f1(str):
    global sports
    if str.upper() == "EXIT":
        sys.exit("User exit")
    else:
        sports.append(str)
        sys.exit()

user = ['zhangkai','jiakai','liming']
for usr in user:
    sports = []
    print(usr + ",input your favorite sport and type exit tp exit.")
    while True:
        response = input(":")
        try:
            f1(response)
        except SystemExit as msg:
            print(msg)
            print(usr + "'s favorite sports is " + ",".join(i.lower() for i in sports) + '.')
            break
#Author:Anliu
import sys
print(sys.path)
sys.path.append("自定义路径")
#Author:Anliu
import sys
#print(sys.path)
#sys.path.append("自定义路径")

#print(sys.modules.keys())
#print(sys.platform)
#print(sys.stdout.write)
#

print('Dive in')
saveout = sys.stdout
with open("out.put","w") as f:
    sys.stdout = f
    print("This is a test from logging")
sys.stdout = saveout
print("123")

shuti模块:高级的 文件、文件夹、压缩包 处理模块

#Auth: Anliu
import os,shutil
with open("file1","w",encoding="utf-8") as f:
    f.write("This is a test from linux")
with open("file2","w",encoding="utf-8") as f:
    f.write("This is a test from python")
#shutil.copymode("file1","file2")  #仅拷贝权限。内容、组、用户均不变
#shutil.copystat("file1","file2")  #拷贝状态的信息,包括:mode bits, atime, mtime, flags
#shutil.copy("file1","file2")   #拷贝文件和权限
#shutil.copy2("file1","file2")  #拷贝文件和状态信息
#os.makedirs(r"root/123/aaa/bbb")
#shutil.copytree("root","root1",ignore= shutil.ignore_patterns("*.xls","*.doc")) #递归的去拷贝文件
#shutil.rmtree("root")     #递归的去删除文件
#shutil.move("root1","root2")     #递归的去移动文件
'''
创建压缩包并返回文件路径,例如:zip、tar
base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户,默认当前用户
group: 组,默认当前组
logger: 用于记录日志,通常是logging.Logger对象
'''
shutil.make_archive("root2","tar","root2")

shelve模块:

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

#Author:Anliu
import shelve,time
d = shelve.open("file")

list = ["linux",["base","auto"]]
d["name"] = "anliu"
d["list"] = list
d["time"] = time.localtime()

print(d.get("list"))
print(d.get("name"))

 

posted @ 2020-04-08 22:48  大江东流水  阅读(608)  评论(0编辑  收藏  举报