python-常用模块

什么是模块:
  模块实质上就是一个python文件,它是用来组织代码的,意思就是说把python代码写到里面,文件名就是模块的名称,test.py:test就是模块名称。

一、os模块:对操作系统的一些操作

import os   #对操作系统一些操作
print(os.getcwd())  #获取当前工作目录
os.chmod('h.py',2)   #给文件加目录,对windons不好使,只对Linux有用(1执行,2写,4读)
print(os.chdir("../"))    #更改当前目录,。'../'表示上一级目录
print(os.chdir("['E:/BestTest/BestTest1/day5']"))
print(os.makedirs('a/b'))   #创建文件夹
print(os.mkdir('a/b'))     #创建文件夹
# makedirs 如果父目录不存在会自动帮你创建目录, mkdir 如果父目录不存在会报错

print(os.removedirs('a/b'))    #递归删除文件夹
print(os.rmdir('b'))    #只能删除文件夹
# 只能删除空目录

print(os.listdir('e:\\'))   #列出目录下所有的文件和文件夹
os.remove('a.txt'))         #只能删除文件,不可删除文件夹
print(os.rename('old','new')#重命名
print(os.sep)               #当前操作系统的路径分隔符
print(os.linesep)           #当前操作系统的换行符  linux下\n  Windows下\r\n
print(os.pathsep)           #当前系统的环境变量中每个路径的分隔符,Linux是:, windows是;
print(os.environ)           #当前系统的环境变量
print(os.name)              #当前系统名称  Windows系统都是nt,Linux系统都是posix
res=os.system('ipconfig')   #执行操作系统命令的,但是获取不到结果
res=os.popen('ipconfig').read()      #可以获取到命令执行的结果
print(os.path.abspath(__file__))     #获取绝对路径,__file__获取到当前文件的绝对路径
print(os.path.split('BestTest/BestTest1/day6/常用模块.py'))
print(os.path.dirname("e:\\syz\\ly-code"))      #获取父目录,获取它的上一级目录
print(os.path.basename("e:\\syz\\ly-code"))     #获取它的最后一级
print(os.path.exists(r"E:\syz\ly-code\day6"))   #判断文件或者目录是否存在
print(os.path.isabs('../day5'))         #判断是否是绝对路径
print(os.path.isfile("xiaohei.py "))    #判断是否是一个文件,1、文件要存在2、必须是一个文件
print(os.path.isdir("e:\\syz1"))        #是否是一个路径,目录是否存在
size = os.path.getsize('x.py')          #获取文件的大小,不能超过2m
print(size)
os.path.join("root",'hehe','mysql','a.sql')  #拼接路径

for abs_pash,dir,data in os.walk('E:/BestTest/BestTest1/day6'):
    print(abs_pash,dir,data)
  # abs_path 当前循环的绝对路径
  # dir 目录下面所有的文件夹 [ ]
  #  file 目录下面的所有文件  []

 

二、sys模块

print(sys.platform)    #判断操作系统
print(sys.path)       #python的环境变量

sys.path.append('../day5')    #加入到环境变量中最后一位
sys.path.insert('../day5')    #加入到环境变量中第一位,效率更高

print(sys.argv)    #用来获取命令行里面运行python文件的时候传入的参数

 

三、Python导入模块的时候的顺序:

  1.从当前目录下找需要导入的Python文件

  2.从Python的环境变量中找  

当前目录导入:

 新建Python文件“hh”(导入时直接写文件名即可):

方法1:

import hh
print(hh.name)    #使用方法:模块名.XX
hh.my()

方法2:

form hh import my,name    #import * 导入所有的
my()
print(name)

 

 

四、xlmt(写Excel)模块

import xlwt

book = xlwt.Workbook()              #新建一个excel
sheet = book.add_sheet('sheet1')    #加sheet页
sheet.write(0,0,'姓名')              #行、列、写入的内容
sheet.write(0,1,'年龄')
sheet.write(0,2,'性别')
book.save('stu.xls')                 #结尾一定要用.xls

 

五、pymysql模块

python操作mysql数据库 python3中操作mysql数据需要安装一个第三方模块,pymysql,使用pip install pymysql安装即可,在python2中是MySQLdb模块,在python3中没有MySQLdb模块了,所以使用pymysql。

连接数据库的步骤:

  1.链接数据库:账号、密码、ip、端口号、数据库;

  2.建立游标;

  3.执行sql(执行insert、delete、update语句时,必须得commit)

  4.获取结果;

  5.关闭游标;

  6.连接关闭;

import pymysql

coon=pymysql.connect(host='118.24.3.40',user='jxz',passwd='123456',port=3306,db='jxz',charset='utf8')
#port必须写int类型
#charset这里必须写utf8
cur=coon.cursor()  #建立游标
cur.execute('select * fron stu')   #执行sql语句
res = cur.fetchall()    #获取所有返回结果
cur.close()   #关闭游标
coon.close()  #关闭连接

 

六、time/datatime模块

时间的三种表达方式:

  1.时间戳:从unix元年到现在过了多少年

  2.格式化好的时间,例如:2018-05-04

  3.时间元祖

print(time.time())  #获取当前时间戳
time.sleep(10)
today = time.strftime('%Y%m%d%H%M%S')   #获取格式化好的时间
print(time.gmtime()) #默认取的是标准时区的时间
print(time.localtime()) #取到的是当前时区的时间
res=datetime.date.today()+datetime.timedelta(days=5)  #获取5天后的时间,-5是5天前的时间,minutes,weeks
print(res)

时间戳转换格式化时间

  1.先把时间戳转换成时间元祖

  2.再把时间元祖装换成格式化好的时间

s =time.localtime(1524299387.2033713)
print(time.strftime('%Y-%m-%d %H:%M:%S',s))

将时间戳转换成格式化时间的函数

def timetamp_to_fomat(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
    #默认返回当前格式化好的时间
    #传入时间戳的话,把时间戳转换成格式化好的时间,返回
    if timestamp:
        time_tuple=time.localtime(timestamp)
        res=time.strftime(format,time_tuple)
    else:
        res=time.strftime(format)
    return res

print(timetamp_to_fomat())
print(timetamp_to_fomat(197323242))

 

格式化时间转换时间戳

  1.先把格式化好的时间转成时间元祖

  2.再把时间原则转成时间戳

tp=time.strptime('2018-4-21','%Y-%m-%d')  #把格式化好的时间转成时间元祖的
time.mktime(tp)  #把时间元祖转成时间戳

将格式化时间转成时间戳的函数

def strToTimestamp(str=None,format='%Y-%m-%d %H:%M:%S'):
    if str:    #如果传了时间的话
        tp=time.strptime(str,format)   #格式化好的时间,转成时间元组
        res=time.mktime(tp)     #转成时间戳
        print (res)
    else:
        res=time.time()   #默认当前的时间戳
    return int(res)

print(strToTimestamp())
print(strToTimestamp('2018-04-23','%Y-%m-%d'))

datetime

import datetime
datetime.datetime.today() #获取当前时间,精确到秒
datetime.date.today()    #获取当前时间,精确到天
res=datetime.date.today()+datetime.timedelta(days=5)  #获取5天后的时间,-5是5天前的时间,minutes,weeks
print(res)

 

七、hashlib模块

m =hashlib.md5()    #实例化md5对象
print(m.__doc__)     #__doc__ 打印帮助文档
passwd ='hr123456'
passwd.encode()    #把字符串转成bytes类型
#加密必须得是bytes类型
m.update(passwd.encode())  #不能直接对字符串加密,要先把字符串转成bytes类型
print(m.hexdigest())
#md5是不可逆的

将加密写成函数

def my_md5(str):
    import hashlib
    new_str = str.encode()  #把字符串转成bytes类型
    # new_str = b'%s'%str   #把字符串转成bytes类型
    m = hashlib.md5()      #实例化md5对象
    m.update(new_str)      #加密
    return m.hexdigest()    #获取结果返回

 

八、xpinyin(拼音)模块

import xpinyin
p = xpinyin.Pinyin()  #实例化
res = p.get_pinyin('烘干')  #默认不传后面的话,两个拼音之间会有- 链接
print(res)
print(p.get_pinyin('烘干',''))  #汉字转成拼音

 

九、random模块

import random,string
print(random.randint(1,10))#随机取整数
print(random.uniform(1,99),2)#随机取2位小数
print(random.choice([1,2,3,4,5]))#只能随机取1个元素
print(random.sample(string.printable,5))#代表数字,字母和特殊字符
print(random.randint(1,1000))#随机产生一个1-1000的数字
print('1'.zfill(4))#补0  生成4位数,不够在前面补0 ,前面''中必须是字符串
#洗牌,打乱顺序
pickts =['A','J','Q','K',2,3,4,5,6]
random.shuffle(pickts)
print(pickts)

 

posted @ 2018-05-04 15:58  小黄同学。  阅读(397)  评论(0)    收藏  举报