python常用模塊

1.模塊和包

● 模塊定義:用來從邏輯上組織python代碼(變量,函數,類,邏輯:實現一個功能),本質就是.py結尾的python文件(文件名test.py,對應的模塊名:test)

● 包定義:用來從邏輯上組件模塊的,本質就是一個目錄(必須帶有一個__init__.py文件)


2.模塊和包導入本質

● 導入模塊的本質就是把python文件解釋一遍

● 導入包的本質就是執行該包下的__init__.py文件;如果要導入包下面的模塊:需要先導入包,然後包下的__init__.py文件中再導入該包下的模塊


3.導入模塊

import module_name                            #導入一個模塊
import module1_name,module2_name              #導入多個模塊
module_name.logger()                           #執行模塊裏的函數
modele_name.var                                #調用模塊裏的變量

from module_name import method1 method2
from module_name import *                   #導入模塊的所有方法,不建議用
logger()                                       #直接調用模塊裏的方法 ,不用模塊名加點

from module_name import logger as logger_feng         #導入將模塊裏的logger方法並改名


4.導入不同包(目錄)下的python模塊

import os,sys
#print(__file__)                                 #動態獲取當前文件相當路徑
#print(os.path.abspath(__file__))                        #動態獲取當前文件絕對路徑
#print(os.path.dirname(os.path.abspath(__file__))                         #動態獲取當前文件父目錄路徑
PATH=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))                 #這裏獲取到的是ATM這個目錄的絕對路徑
sys.path.append(PATH)                               #將獲取到的絕對路徑加到環境變量
from core import main                             #從core目錄下import main
main.name("fengxiaoli")                              #調用main裏的函數name

5.time模塊

python中通常時間的表示

●時間戳

格式化的時間字符串

元組時間

222.png

●時間戳-->元組時間

>>> x = time.time()                           #獲取當前時間戳
>>> time.gmtime(x)                            #將當前時間戳轉化爲utc時間元組
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=4, tm_hour=10, tm_min=4, tm_sec
=22, tm_wday=6, tm_yday=35, tm_isdst=0)
>>> time.localtime(x)                           #將當前時間戳轉化爲本地時間(utc+8)元組
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=4, tm_hour=18, tm_min=4, tm_sec
=22, tm_wday=6, tm_yday=35, tm_isdst=0)

>>> x1 = time.localtime(x)
>>> x1.tm_year                                   #獲取元組時間
2018
>>> x1.tm_mon
2


元組時間-->時間戳

>>> x1
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=4, tm_hour=18, tm_min=4, tm_sec
=22, tm_wday=6, tm_yday=35, tm_isdst=0)
>>> time.mktime(x1)
1517738662.0

元組時間-->自定義格式化字符串時間

>>> x1
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=4, tm_hour=18, tm_min=4, tm_sec
=22, tm_wday=6, tm_yday=35, tm_isdst=0)
>>> time.strftime("%Y-%m-%d %H:%M:%S",x1)
'2018-02-04 18:04:22'

●自定義格式化字符串時間-->元組時間

>>> help(time.strptime)       #查看strptime幫助
strptime(...)
    strptime(string, format) -> struct_time

>>> time.strptime("2018-02-04 18:04:22","%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=4, tm_hour=18, tm_min=4, tm_sec
=22, tm_wday=6, tm_yday=35, tm_isdst=-1)


333.png

●時間戳-->格式化字符串

>>> x
1517738662.821426
>>> time.ctime(x)
'Sun Feb  4 18:04:22 2018'

●元組-->格式化字符串

>>> x1
time.struct_time(tm_year=2018, tm_mon=2, tm_mday=4, tm_hour=18, tm_min=4, tm_sec
=22, tm_wday=6, tm_yday=35, tm_isdst=0)
>>> time.asctime(x1)
'Sun Feb  4 18:04:22 2018'


time模塊其他方法

>>> import time
>>> time.timezone                   #標準時間(utc)和本地時間(utc+8)相差多少秒
-28800                              #這裏是本地時間比標準時間早28800秒,也就是早8小時,也就是中國爲utc+8時區
>>> 28800/3600
8.0

>>> time.altzone                   #標準時間和夏令時相差多少
-32400
>>> time.daylight                   #判斷是否是夏令時
0

>>> time.clock()                    #當運行time.clock()開始,返回一個時間
1.0263524545646598e-05
>>> time.clock()
2.1054247858986015
>>> time.clock()
3.8245134020248224
>>> time.clock()
6.940938975648932
>>> time.clock()
15.189280774964526

>>> time.sleep(2)                 #程序睡2秒
>>> time.sleep(1)

>>> time.time()                    #返回一個時間戳,該時間戳是從1970到現在多少秒
1517737506.325569
>>> x=time.time()
>>> x/3600/24/365
48.12714301673213
>>> 1970+48
2018

6.datetime模塊

>>> import datetime
>>> print(datetime.datetime.now())                         #獲取當前時間
2018-02-04 18:37:25.319604

>>> print(datetime.date.fromtimestamp(time.time()))                #將時間戳改爲格式化字符串
2018-02-04

>>> print(datetime.datetime.now() + datetime.timedelta(3))            #當前時間+3天
2018-02-07 18:40:59.8228
>>> print(datetime.datetime.now() + datetime.timedelta(-3))           #當前時間-3天
2018-02-01 18:41:06.402249
>>> print(datetime.datetime.now() + datetime.timedelta(hours=3))         #當前時間加3小時
2018-02-04 21:41:29.079546
>>> print(datetime.datetime.now() + datetime.timedelta(minutes= -3))      #當前時間減3分鐘
2018-02-04 18:38:40.102177

>>> c_time = datetime.datetime.now()
>>> print(c_time.replace(minute=3,hour=2))                     #更改時間
2018-02-04 02:03:47.909055

7.random模塊

#隨機浮點數
>>> import random
>>> random.random()                         #生成一個0-1的隨機浮點數
0.7370268365256588
>>> random.uniform(1,3)                           #隨機打印1-3直接的浮點數
2.907184937455974
>>> random.uniform(1,5)
3.1441005290312556


#隨機整數
>>> random.randint(1,5)                                       #生成一個1-5的隨機整數,包括1和5
5
>>> random.randint(1,5)
2

#隨機選取0-100間的偶數
>>> random.randrange(0,101,2)
6

>>> random.randrange(1,5)                                    #生成一個1-4的隨機整數,不包括5
3
>>> random.randrange(1,5)
4

#隨機字符
>>> random.choice("hello")                                #隨機打印一個前面對象的元素
'o'
>>> random.choice([1,2,3,4])
2

#多個字符選取特定數量字符
>>> random.sample("hello",2)                               #指定個數隨機打印前面對象元素
['l', 'o']
>>> random.sample([1,2,3,4],2)
[3, 4]


#洗牌
>>> x = [1,2,3,4,5]
>>> random.shuffle(x)                       #將列表隨機打亂
>>> print(x)
[3, 1, 2, 4, 5]

#驗證碼,生成4位隨機驗證碼
import random
n = 4
checkcode = ""
for i in range(n):
    current = random.randrange(0,n)
    if i < current:
        tmp = random.randint(0,9)
    elif i==current:
        tmp = chr(random.randrange(97, 122))
    else:
        tmp = chr(random.randrange(65,90))
    checkcode+=str(tmp)
print(checkcode)

8.os模塊

#提供對操作系統進行調用的接口

#對目錄操作
os.getcwd()                      #獲取當前工作目錄,即當前python腳本工作的目錄路徑
os.chdir("dirname")                      #改變當前腳本工作目錄;相當於shell下cd
os.curdir                        #返回當前目錄: ('.')
os.pardir                        #獲取當前目錄的父目錄字符串名:('..')
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.sep                          #輸出操作系統特定的路徑分隔符,win下爲"\\",Linux下爲"/"
os.linesep                        #輸出當前平臺使用的行終止符,win下爲"\r\n",Linux下爲"\n"
os.pathsep                        #輸出用於分割文件路徑的字符串
os.name                         #輸出字符串指示當前使用平臺。win->'nt'; Linux->'posix'

os.system("bash command")                     #運行shell命令,直接顯示
os.environ                       #獲取系統環境變量

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所指向的文件或者目錄的最後修改時

9.sys模塊

import sys
print(sys.argv)         #以list格式返回該腳本參數,返回的第一個參數是執行該腳本相當路徑
如:python test.py 1 2 3
['test.py','1','2','3']

sys.exit(n)         #退出程序,正常退出時exit(0)
sys.version         #獲取python版本
sys.path            #返回模塊搜索路徑,初始化時使用pythonpath環境變量的值
sys.platform         #返回操作系統平臺
sys.stdout.write("--")     #標準輸出到屏幕

10.shutil模塊

#高級的 文件、文件夾、壓縮包 處理模塊

import shutil

f1 = open("file1","r",encoding="utf-8")
f2 = open("file2","w",encoding="utf-8")
shutil.copyfileobj(f1,f2)                     #複製文件1內容到文件2,需要自己打開關閉文件


shutil.copyfile("file1","file2")               #複製文件1內容到文件2,不需要自己打開關閉文件
shutil.copymode("file1","file2")               #僅拷貝權限,內容,組,用戶均不變
shutil.copystat("file1","file2")                 #拷貝狀態的信息,包括 mode bits,atime,mtime,flags
shutil.copy("file1","file2")                   #拷貝文件和權限
shutil.copy2("file1","file2")                   #拷貝文件和狀態信息
shutil.copytree("srcdir","dstdir")                #遞歸的拷貝文件
shutil.rmtree("dstdir")                      #遞歸刪除文件
shutil.move("src","dst")                     #遞歸的去移動文件


shutil.make_archive("base_name", format,...)           #創建壓縮包並返回文件路徑,例如:zip、tar

base_name:壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑。
format:壓縮包種類,“zip”, “tar”, “bztar”,“gztar”
root_dir:要壓縮的文件夾路徑(默認當前目錄)
owner:用戶,默認當前用戶
group:組,默認當前組
logger:用於記錄日誌,通常是logging.Logger對象


11.zipfile模塊

import zipfile
impot os


#壓縮單個文件
import zipfileimport 
oswith zipfile.ZipFile('test.zip', 'w') as z:
    z.write('log.txt')  



#壓縮某個目錄下所有文件
def compress_file(zipfilename, dirname):                              # zipfilename是壓縮包名字,dirname是要打包的目錄/文件
    if os.path.isfile(dirname):
        with zipfile.ZipFile(zipfilename, 'w') as z:
            z.write(dirname)
    else:
        with zipfile.ZipFile(zipfilename, 'w') as z:
            for root, dirs, files in os.walk(dirname):        #這裏用到了os.walk遍歷目錄下的文件,詳情參考os的walk方法
                for single_file in files:
                    if single_file != zipfilename:
                        filepath = os.path.join(root, single_file)
                        z.write(filepath)
                        
compress_file('a.zip', '.')                                                #執行函數  



#添加文件到已有的zip包中
def addfile(zipfilename, dirname):
    if os.path.isfile(dirname):
        with zipfile.ZipFile(zipfilename, 'a') as z:
            z.write(dirname)
    else:
        with zipfile.ZipFile(zipfilename, 'a') as z:
            for root, dirs, files in os.walk(dirname):
                for single_file in files:
                    if single_file != zipfilename:
                        filepath = os.path.join(root, single_file)
                        z.write(filepath)

addfile('a.zip', 'test.txt')



#查看壓縮包中的文件
def viewfile(zipfilename):
    with zipfile.ZipFile(zipfilename, 'r') as z:
        print(z.namelist())

viewfile('a.zip')

                         

#解壓
with zipfile.ZipFile('test.zip', 'r') as z:
    print(z.namelist())                                     # 查看壓縮包中的文件列表
    # print(z.read(z.namelist()[0]))                              # 讀出來壓縮包中的第一個文件的內容打印到屏幕,也可保存到文件中
    z.extractall('C:\\Users\\Administrator\\PycharmProjects\\aaa')                         # 解壓,可設置解壓路徑
    # z.extract('log.txt')                                   # 解壓,可選擇解壓壓縮包中的某個文件
    #z.extractall()                                       # 解壓全部


12.tarfile模塊

import tarfile
import os

#壓縮文件
with tarfile.open('a.tar', 'w') as tar:
    tar.add('log.log', arcname='log.log')
    tar.add('test.txt', arcname='test.txt')


#解壓文件
with tarfile.open('a.tar', 'r') as tar:
    print(tar.getmembers())                                      # 查看壓縮包內文件成員
    # tar.extract('test.txt')                                    # 可選擇解壓某個文件
    # tar.extractall('ccc')                                      # 可設置解壓路徑
    tar.extractall()                                             # 解壓全部

		
#壓縮某個目錄下所有文件	
def compress_file(tarfilename, dirname):                         # tarfilename是壓縮包名字,dirname是要打包的目錄
    if os.path.isfile(dirname):
        with tarfile.open(tarfilename, 'w') as tar:
            tar.add(dirname)
    else:
        with tarfile.open(tarfilename, 'w') as tar:
            for root, dirs, files in os.walk(dirname):
                for single_file in files:
                    # if single_file != tarfilename:
                    filepath = os.path.join(root, single_file)
                    tar.add(filepath)

compress_file('test.tar', 'test.txt')
compress_file('t.tar', '.')



#添加文件到已有的tar包中
def addfile(tarfilename, dirname):                                # tarfilename是壓縮包名字,dirname是要打包的目錄
    if os.path.isfile(dirname):
        with tarfile.open(tarfilename, 'a') as tar:
            tar.add(dirname)
    else:
        with tarfile.open(tarfilename, 'a') as tar:
            for root, dirs, files in os.walk(dirname):
                for single_file in files:
                    # if single_file != tarfilename:
                    filepath = os.path.join(root, single_file)
                    tar.add(filepath)

addfile('t.tar', 'ttt.txt')
addfile('t.tar', 'ttt')


13.xml模塊

import xml.etree.ElementTree as ET              #導入xml模塊並取別名

tree = ET.parse("xml_test.xml")                 #找到xml文件內存地址
root = tree.getroot()                           #找到xml文件根內存地址
print(root.tag)                                 #打印xml文件根標籤

# 遍歷xml文檔
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag, i.text,i.attrib)

# 只遍歷year 節點
for node in root.iter('year'):
    print(node.tag, node.text)

    
    
    
    
#修改和刪除xml文檔內容
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()

# 修改
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated", "yes")

tree.write("xmltest.xml")

# 刪除node
for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)

tree.write('output.xml')

#自己創建xml文件
import xml.etree.ElementTree as ET

new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'

et = ET.ElementTree(new_xml)  # 生成文檔對象
et.write("test.xml", encoding="utf-8", xml_declaration=True)

ET.dump(new_xml)              # 打印生成的格式


14.configparser模塊

#將字符寫爲配置文件的形式
import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']

topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here

config['DEFAULT']['ForwardX11'] = 'yes'

with open('example.ini', 'w') as configfile:
    config.write(configfile)



#讀configparser文件
import configparser
conf =configparser.ConfigParser()
conf.read("example.ini")

# print(conf.defaults())
# print(conf["bitbucket.org"]["user"])
# #print(conf.sections())
for i in conf["topsecret.server.com"]:
    print(i)



#刪除
import configparser
conf =configparser.ConfigParser()
conf.read("example.ini")
sec=conf.remove_section("bitbucket.org")
conf.write(open("example.cfg","w"))


#改寫
import configparser
conf =configparser.ConfigParser()
conf.read("example.ini")
sec=conf.remove_section("bitbucket.org")
sec=conf.add_section("fengxiaoli.org")
sec=conf.set("fengxiaoli.org","k1","111")

conf.write(open("example.cfg","w"))


14.re模塊

# re.match 從頭開始匹配 ,返回一個

# re.search 匹配包含,返回一個

# re.findall 把所有匹配到的字符放到以列表中的元素返回,返回所有

# re.splitall 以匹配到的字符當做列表分隔符

# re.sub      匹配字符並替換

import re

#match方法
c="chen234feng3252cxasfgj54gvf"
res1=re.match("chen",c)
res2=re.match("^chen\d+",c)
res3=re.match(".+",c)
#res4=re.match("cx",c)  #匹配不到cx,因爲re.match只能從頭開始匹配
print(res1.group())
print(res2.group())
print(res3.group())
#print(res4.group())

#search方法
c="chen234fengdfasfcx3252cxasfgj54gvf"
res1=re.search("cx",c)
res2=re.search("feng.*cx",c)
res3=re.search("^chen.+cx",c)
res4=re.search("feng[a-z]+cx",c)
res5=re.search("[0-9]{3}",c)  #匹配連續出現3次數字的字符
res6=re.search("[0-9]{1,3}",c)  #匹配連續出現數字,1次到3次的字符,re.search只能返回一個
res7=re.search("(abc){2}","fengabcabcffcxabc")  #將abc分組,匹配連續出現兩次的abc
print(res1.group())
print(res2.group())
print(res3.group())
print(res4.group())
print(res5.group())
print(res6.group())
print(res7.group())


#分組匹配  '(?P<name>...)'
res10=re.search("(?P<id>[0-9]+)(?P<name>[a-zA-Z]{4})",c).groupdict()
print(res10)
#輸出
{'id': '234', 'name': 'feng'}


res11=re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})", "371481199306143242").groupdict()
#結果
print(res11)
#{'province': '3714', 'city': '81', 'birthday': '1993'}


#findall方法
c="c1hen234fengdfas1fcx3252cxasfgj54gvf"
res1=re.findall("cx",c)
res2=re.findall("feng|cx",c)
res6=re.findall("[0-9]{1,3}",c)
print(res1)
print(res2)
print(res6)


#split方法
res=re.split("[0-9]","dsf34dsf46kjl6")  #按指定字符分割
res1=re.split(":","dsf:34ds:f46kjl6")
print(res)
print(res1)


#sub方法
res=re.sub("[0-9]+","AAA","afd454dffb56756sdg11feng") #將匹配的字符替換爲指定字符
res1=re.sub("[0-9]+","AAA","afd454dffb56756sdg11feng",count=2) #指定替換的次數
print(res)
print(res1)


注:
# re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)
# M(MULTILINE): 多行模式,改變'^'和'$'的行爲
# S(DOTALL): 點任意匹配模式,改變'.'的行爲

#res1=re.search("fengxiaoli","\nFengXiaoLi123Cx456\nKdf564",flags=re.I)  #忽略大小寫
#res1=re.search("^Feng","\nFengXiaoLi123Cx456\nKdf564",flags=re.M)   #
res1=re.search("Cx.+564","\nFengXiaoLi123Cx456\nKdf564",flags=re.S)  #默認點不能匹配\n,加上re.S後可以
print(res1.group())








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章