time模塊:
在python中,通常有以下幾種方式來表示時間:
1、時間戳,如time.time
2、格式化的時間字符串,如'17/01/2017 10:17:00'
3、元組(struct_time),如gmtime、localtime等等
time.time():把從1970年開始到現在的所有時間轉換成秒數,即時間戳
time.gmtime():將時間戳(秒數)轉換成UTC時區的元組形式
time.localtime():將時間戳轉換成當地時區的元組形式
這種元組形式的時間可以通過其內部的方法取得需要的時間元素。例:
x = time.localtime()
x.tm_year可以取得當前是哪一年
x.tm_mon可以取得當前是哪一月
x.tm_mday可以取得當前是哪一天
time.sleep(s):睡眠s秒
time.mktime(t):將元組(tuple)形式的時間轉換成時間戳
time.strftime(format [, tuple]):
將元組形式的時間轉換成格式化的時間字符串(用數字方式顯示),若不指定tuple則轉換當前的localtime
time.strptime(string, format):將格式化的時間字符串轉換成元組形式的時間
time.asctime([tuple]):
將元組形式的時間轉換成格式化的時間字符串(用英文方式顯示),若不指定tuple則轉換當前的localtime
time.ctime([seconds]):
將時間戳轉換成格式化的時間字符串(用英文方式顯示),若不指定時間戳則轉換當前的時間戳
datetime模塊:
datetime.datetime.now():取得當前的日期與時間
datetime.datetime.now() + datetime.datetime.delta(3):取得三天後的當前時間
datetime.datetime.now() + datetime.datetime.delta(-3):取得三天前的當前時間
datetime.datetime.now() + datetime.datetime.delta(hours=3):取得三小時後的當前時間
datetime.datetime.now() + datetime.datetime.delta(hours=-3):取得三小時前的當前時間
datetime.datetime.now().replace(minute=10,hour=10):時間替換
random模塊:隨機數
random.random():取得0-1之間的浮點隨機數
random.uniform(1,10):取得1-10之間的浮點隨機數,1和10可以任意指定
random.randint(1,3):取得1-3之間的任意隨機數,包括1和3,這裏的1和3可以任意指定
random.randrange(1,3):取得1-3之間的任意隨機數,不包括3,這裏的1和3可以任意指定
random.choice('equence):從序列sequence中隨機取一個元素
random.sample(sequence,count):每次從序列sequence中隨機取count個元素
random.shuffle(sequence):洗牌,將一個序列的順序打亂
os模塊:提供對操作系統進行調用的接口
os.getcwd():獲取當前工作目錄
os.chdir(path):切換目錄
os.curdir:返回當前目錄
os.pardir:返回當前目錄的父目錄
os.makedirs(name, mode=511, exist_ok=False):遞歸創建目錄
例:os.makedirs(r'/a/b/c/d/e')
os.removedirs(name):若目錄爲空則刪除,並遞歸到上一級目錄,若還是爲空則再刪除,依此類推
os.mkdir(path, mode=511, *, dir_fd=None):創建單級目錄,若父目錄不存在則拋出異常
os.rmdir(path, *, dir_fd=None):刪除單級空目錄,若目錄不爲空則拋出異常
os.listdir(path=None):列出某路徑下的所有文件,包括文件和目錄
os.remove():刪除一個文件
os.rename('oldname','newname'):重命名文件/目錄
os.stat('path/to/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.popen('bash command'):運行shell命令,命令結果作爲返回值返回並打印至屏幕
os.startfile('/path/to/file'):以圖形化方式打開一個程序,只適用於windows
os.environ:獲取系統環境變量
os.urandom(n):返回指定n字節的加密強隨機數據
os.path.abspath(path):返回path規範化的絕對路徑
os.path.split(path):返回將path分割成以目錄和文件名作爲元素的2元素元組
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,否則返回False
os.path.isabs(path):判斷path是不是一個絕對路徑,是則返回True,否則返回False
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所指向的文件或目錄的最後修改時間
sys模塊:提供對python進行調用的接口
sys.argv:命令行參數list,第一個元素是程序本身路徑
sys.exit(n):退出程序,正常退出時exit(0),n可以是數字也可以是字符串
sys.version:獲取python解釋程序的版本信息
sys.maxint:最大的int值
sys.path:返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform:返回操作系統平臺名稱
sys.stdout.write('please: ')
va1 = sys.stdin.readline()[:-1]
sys.modules:返回當前系統已加載的所有模塊信息字典
fileinput:遍歷文本文件所有的行
fileinput.input(/path/to/file):返回一個可迭代的文件流類的實例對象
fileinput.filename():返回當前文件名
fileinput.lineno():返回當前行號
fileinput.filelineno():返回文件行數
fileinput.isfirstline():判斷當前行是不是文件的第一行
fileinput.isstdin():檢查最後一行是否來自於標準輸入流
fileinput.nextfile():關閉當前文件並將指針移動到下一個文件
fileinput.close():關閉所有已打開的文件
shutil:專門用來copy文件,可以壓縮包
shutil.copyfileobj(fsrc,fdst [, length]):
將ffsrc的內容拷貝至fdst中,可以通過length設置拷貝多少內容
shutil.copyfile(src,dst):拷貝src至dst
shutil.copymode(src,dst):僅拷貝權限。新文件的內容、組、用戶均不變(誰創建的文件就是誰的)
shutil.copystat(src,dst):拷貝狀態的信息,包括mode bits,atime,mtime,flags
shutil.copy(src,dst):拷貝文件和權限
shutil.copy2(src,dst):拷貝文件和狀態信息
shutil.copytree(src,dst,symlink=False,ignore=None):遞歸的去拷貝文件
shutil.rmtree(path [, ignore_errors [, onerror]]):遞歸的去刪除文件
shutil.move(src,dst):遞歸的去移動文件
shutil.make_archive(base_name,format,...):創建壓縮包並返回文件路徑,例如:zip、tar
base_name:
壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑。
如:www => 保存至當前路徑
如:/Users/sean/www => 保存至/Users/sean/www
format:壓縮包種類。'zip'、'tar'、'bztar'、'gztar'
root_dir:要壓縮的目錄路徑(默認當前目錄)
owner:用戶。默認當前用戶
group:組。默認當前組
logger:用於記錄日誌。通常是logging.Logger對象
shutil對壓縮包的處理是調用ZipFile和TarFile兩個模塊來進行的。
zipfile模塊:
壓縮:
z = zipfile.ZipFile('test.zip','w')
z.write('a.log')
z.write('data.data')
z.close()
解壓:
z = zipfile.ZipFile('test.zip','r')
z.extractall()
z.close()
tarfile模塊:
壓縮:
tar = tarfile.open('your.tar','w')
tar.add('/Users/sean/www.zip',arcname='www.zip')
tar.add('/Users/sean/cmdb.zip',arcname='cmdb.zip')
tar.close()
解壓:
tar = tarfile.open('your.tar','r')
tar.extractall()
tar.close()
json & pickle:用於序列化的兩個模塊
json,用於字符串和python數據類型間進行轉換
把python內存中的數據類型轉換成字符串存儲在硬盤的文件上
解決了不同語言、不同平臺之間的數據交換問題。
pickle,用於python特有的類型和python的數據類型間進行轉換
把python內存中的任意數據類型轉換成字符串存儲在硬盤的文件上
兩者均提供了四個功能:dumps、dump、loads、load
dumps和loads直接在內存中操作,不對文件進行操作
dump和load會對文件進行操作:寫入和讀取
shelve:一個簡單的字典類型的(key,value),將內存數據通過文件持久化存儲的模塊
可以持久化存儲任何pickle可支持的python數據類型
寫入:
1
2
3
4
5
6
7
8
9
10
11
|
d = shelve. open ( 'shelve_test' ) #打開一個文件 class Test( object ): def __init__( self ,n): self .n = n t = Test( 123 ) t2 = Test( 1234567 ) name = [ 'tom' , 'jerry' , 'test' ] d[ 'test' ] = name #持久化列表 d[ 't1' ] = t #持久化類 d[ 't2' ] = t2 d.close() |
讀取:
1
2
3
|
d.get( 'test' ) d.get( 't1' ) d.get( 't2' ) |
xml:用來在python中處理xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import xml.etree.ElementTree as ET tree = ET.parse( 'xmltest.xml' ) #要處理的文件名 root = tree.getroot() print (root.tag) #打印根標籤名 #遍歷xml文檔 for child in root: print (child.tag,child.attrib) for i in child: print (i.tag,i.text) #只遍歷year節點 for node in root. iter ( 'year' ): print (node.tag,node.text) #修改 for node in root. iter ( 'year' ): new_year = int (node.text) + 1 node.text = str (new_year) node. set ( "updated_by" , "sean" ) 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' ) |
configparser:生成和修改常見配置文檔
生成:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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' topsecret[ 'ForwardX11' ] = 'no' config[ 'DEFAULT' ][ 'ForwardX11' ] = 'yes' with open ( 'example.ini' , 'w' ) as configfile: config.write(configfile) |
讀取:
1
2
3
4
|
conf = configparser.ConfigParser() conf.read( 'example.ini' ) print (conf.defaults()) print (conf[ 'bitbucket.org' ][ 'user' ]) |
hashlib:用於加密相關的操作
3.x系列代替了2.x系列中的md5模塊和sha模塊。主要提供SHA1、SHA224、SHA256、SHA284、SHA512和MD5算法
1
2
3
4
5
6
|
import hashlib m = hashlib.md5() m.update(b 'Hello' ) m.update(b "It's me" ) print (m.digest()) #二進制格式hash print (m.hexdigest()) #十六進制格式hash |
注意:前面執行了兩次update,然後纔打印的結果,此時的結果是兩次update的對象加在一起生成的hash
webbrowser:
webbrowser.open(url):打開一個網頁
本文出自 “忘情居” 博客,請務必保留此出處http://itchentao.blog.51cto.com/5168625/1897288