python模組

yepkeepmoving發表於2017-07-30
模組是python非常重要並常用的,這裡對基本用法和常用模組做下簡要記錄
一、模組定義
模組(module):是邏輯上組織python程式碼的.py結尾的Python檔案,程式碼中可以包含變數、函式、類,總體是為了實現一個功能。
包(package):是一個組織python檔案的一個目錄(必須含有一個__init__.py的檔案,用以初始化包內容,所有匯入包裡所有方法,需要在__init__.py中匯入相關方法)
二、模組使用方法
import  module_name
import  module_name01,module_name02
from    module_name import *
from    module_name import fun01,fun02
from    module_name import fun01 as fun

import和from ... import ...的主要區別如下:
  import:相當於當前檔案引用其他檔案的內容,在呼叫匯入模組時,需要呼叫匯入方法,語法必須為modue.fun()帶有匯入模組名
  from ... import ...:相當於匯入模組的所有程式碼直接貼上到當前py檔案,在呼叫時不需要包含模組名,而且可以單獨匯入模組中的部分方法、變數等,但存可能會導致匯入的程式碼和當前程式碼存在變數、方法等衝突問題,慎用
包匯入:import package_name
  匯入包其實就是其執行package_name包下面的__init__.py檔案
三、import本質(路徑搜尋和搜尋路徑)
import 模組的本質是將python檔案解釋一遍,具體流程如下:
import module_name——>module_name.py——>python路徑查詢module_name.py檔案(預設當前路徑先查詢)——>解釋module_name.py或者出錯
#檢視當前python檔案搜尋路徑
import  sys
print(sys.path)

#匯入其他路徑的python模組

  1. import sys
  2. import os
  3. p01=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+os.sep+"Day01"
  4. print(p01)
  5. sys.path.append(p01)
  6. print(sys.path)
  7. import HelloWorld
四、模組分類
1.標準庫(python自帶的)
時間模組:(time、datetime)
##time模組使用方法(格式化字串形式、元組形式、時間戳形式)
import  time
##格式化字串時間格式2017-07-30 11:10:57
print(time.strftime("%Y-%m-%d %X"))
2017-07-30 10:00:24
##時間戳時間格式(1970+time.time()即是當前時間)
print(time.time())
1501377801.9864273

##元組時間格式()
print(time.localtime())
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=30, tm_hour=9, tm_min=25, tm_sec=4, tm_wday=6, tm_yday=211, tm_isdst=0)

time.timezone:標準時間-當前時區值,北京顯示為-28800秒
time.time():
time.sleep():

##時間戳轉化為元組形式
time.gmtime():將秒轉化為UTC的元組形式 ,返回的是標準時間即0時區的當前時間
time.localtime():將秒轉為為UTC元組形式,顯示當前時間,引數值是秒,預設當前時間
##元組轉化為時間戳形式
time.mktime() :將元組形式資料轉化為時間戳形式(秒),傳入的變數值是元組

##元組轉化為格式化的字串時間形式
time.strftime():將元組形式的時間,轉化為格式化的字串形式
x=time.localtime()
print(time.strftime('%Y-%m-%d %X',x))
##字串時間格式轉為元組時間格式
time.strptime():將字串時間格式轉化為元組形式時間格式
x=time.strftime("%Y-%m-%d %X")
print(time.strptime(x,"%Y-%m-%d %X"))

時間格式:
 %Y  Year with century as a decimal number.
 %m  Month as a decimal number [01,12].
 %d  Day of the month as a decimal number [01,31].
 %H  Hour (24-hour clock) as a decimal number [00,23].
 %M  Minute as a decimal number [00,59].
 %S  Second as a decimal number [00,61].
 %z  Time zone offset from UTC.
 %a  Locale's abbreviated weekday name.
 %A  Locale's full weekday name.
 %b  Locale's abbreviated month name.
 %B  Locale's full month name.
 %c  Locale's appropriate date and time representation.
 %I  Hour (12-hour clock) as a decimal number [01,12].
 %p  Locale's equivalent of either AM or PM.

常用獲取當前時間:
time.strftime("%Y-%m-%d %X")
time.localtime()
time.time()

##datetime模組用法

str(datetime.now()+timedelta(3))
'2017-08-04 16:49:51.377186'

str(datetime.now()+timedelta(hours=-3))
'2017-08-01 13:50:51.167165'

str(datetime.now()+timedelta(minutes=+3))
'2017-08-01 18:30:37.745793'

random模組:
##隨機取(0-1)之間的數值
>>> random.random()
0.9151227988883402
##隨機取[m-n]之間的整數
>>> random.randint(1,3)
3
##隨機取[m-n)之間的整數
>>> random.randrange(5)
1
##隨機取一個字元或列表數值
>>> random.choice('chinese')
's'
>>> random.choice([1,5,'abc'])
1
##從字串中隨機取出N個字元
>>> random.sample('hello',2)
['h', 'l']
##從區間(m,n)中取浮點數
>>> random.uniform(3,10)
7.797497264321265

##讓有序列表變無序
>>> l=[1,2,3,4,5]
>>> random.shuffle(l)
>>> l
[2, 4, 1, 5, 3]

案例:生成隨機驗證碼

  1. #!/usr/bin/env python
  2. # -*- UTF-8 -*-
  3. import random

  4. check_code=''

  5. for i in range(4):
  6.     num=random.randrange(0,4)
  7.     if num==i:
  8.         code=chr(random.randint(65,90))
  9.     else:
  10.         code=random.randint(1,9)
  11.     check_code+=str(code)

  12. print(check_code)
##大寫字母ascii:65-90,小寫字母:97-122

OS模組:
os.getcwd()                 ##獲取當前目錄
os.chdir('/home/oracle')        ##切換路徑,前面加r使轉移失效,使用\轉移
os.chdir(r"c:\users")
os.chdir("c:\\users")
os.curdir                ##顯示當前目錄
'.'
os.pardir                ##顯示父目錄
'..'
os.makedirs('/home/tools/a/b')        ##遞迴建立目錄
os.removedirs('/home/tools/a/b')    ##遞迴刪除目錄,如果目錄為空則刪除並遞迴到上層目錄,如果還未空則繼續刪除
os.mkdir('/home/tools/a')          ##建立目錄,不能遞迴建立
os.rmdir('/home/tools/a')        ##刪除目錄,不能遞迴刪除
os.listdir('/')                ##列出目錄內容
os.stat('./.bash_profile')        ##顯示屬性
os.rename('aa','bb')            ##將檔名aa更改為bb
os.linesep                ##顯示平臺使用行終止符號win \r\n linux \n
'\n'
os.sep                    ##輸出作業系統特定的路徑分隔符win \ linux /
'/'
os.name                    ##輸出字元只是當前使用平臺win:nt linux:posix
'posix'
os.pathsep                ##輸出用於分隔檔案路徑的字串windows: ; linux: :
':'
os.environ                ##輸出環境變數
os.system('cmd')            ##執行系統命令,具體命令需要引號括起來,例如os.system('date')
os.path.abspath('abc')          ##獲取檔案abc的絕對路徑
os.path.split('/home/tools/package.zip')##分隔檔名、路徑,結果為('/home/tools', 'package.zip')
os.path.dirname('/home/tools')        ##獲取目錄名稱,最後一個路徑分隔符前的內容
'/home'
os.path.basename('/home/tools')        ##獲取檔名稱,最後一個路徑分隔符後的內容
'tools'
os.path.exists('/home/tools/')      ##判斷檔案、路徑是否存在,返回值為True、False
True
os.path.isabs('/home')            ##判斷是否是絕對路徑
os.path.isfile('/home/package.zip')    ##判斷是否是檔案
True
os.path.isdir('/home')            ##判斷是否為路徑
True
os.path.join('/home','a','b')        ##將多個路徑組合返回
'/home/a/b'
os.path.getatime('/home')        ##獲取檔案、路徑的訪問時間、執行時間
1502700846.897154
os.path.getctime('/home')        ##獲取檔案、路徑的屬性修改時間
1497491543.3123677
os.path.getmtime('/home')        ##後去檔案、路徑的內容修改時間
sys模組:
sys.argv                ##接收輸入變數引數值,列表形式,列表第一個值是檔案本身
 python argv.py  111 222
['argv.py', '111', '222']
sys.exit(n)                ##正常退出程式
sys.version                ##輸出python程式版本資訊
sys.maxint                ##輸出最大int值
sys.path                ##輸出python系統環境變數
sys.platform                ##輸出作業系統平臺
sys.stdout.write("hello \n")        ##系統標準輸出
hi=sys.stdin.readline()[:-1]        ##接收系統標準輸入,不提示;而raw_input(""),提示標準輸入
>>> hi=sys.stdin.readline()[:-1]
hello
>>> print(hi)
hello
>>> he=raw_input("INPUT:")
INPUT:hello
>>> print(he)
hello
shutil模組:


2.第三方模組(開源的)


3.自定義模組(自己定義開發的)



來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/27067062/viewspace-2142786/,如需轉載,請註明出處,否則將追究法律責任。

相關文章