python經常使用模塊

##############經常使用模塊################python

            OS 模塊linux

爲訪問操做系統的特定熟悉提供方法windows

提供了對平臺模塊的封裝(對 windows, 對 mac 的封裝等)ide

os.environ     ##對環境變量的操做測試

os.getcwd()    ##獲取當前的工做目錄spa

os.access(path,mode)  ##判斷一個文件或者目錄是否具備指定的權限操作系統

    mode參數的可選值:ROK,WOK,和X_OKorm

例如:對象

In [7]: os.access('/etc',os.R_OK)blog

Out[7]: True

 

In [8]: os.access('/etc',os.W_OK)

Out[8]: True

 

In [9]: os.access('/etc',os.X_OK)

Out[9]: True

 

 

os.stat()    至關於linux下的stat命令  ##查詢文件和文件系統的詳細信息

os.listdir()       ##列出給定目錄的內容

os.mkdir(path)      ##建立目錄

os.mkdirs(path)    ##建立目錄樹,至關於mkdir-p操做

 

使用python執行linux命令

os.system   ##沒有返回值,是靠反作用產生輸出的

os.popen    ##返回一個文件對象

os.poenp2   ##返回兩個文件對象,一個是stdin,一個是stdout

os.popen3   ##返回三個文件對象:stdin.stdout,stderr

 

 

os.path 是os 的一個子模塊 , 主要是對路徑進行解析、建立、測試和其

他的一些操做,封裝了不一樣平臺的路徑操做。

 

路徑解析:

        path.split('/tem/test/ab')

        path.basename('/tem/test/ab')

        path.dirname('/tem/test/ab')

 wKioL1ls5rqSwpeiAABwvaBw8U4006.png-wh_50

 

 

path.join('a','b','c')

path.abspath('.')

path.splitext('aaa.tar.gz')

 wKiom1ls5tXy44eoAABRrt88Clw607.png-wh_50

 

os.path.getatime ('filename')     ##最後一次訪問文件或目錄的時間

os.path.getctime ('filename')     ##最後一次文件改變或目錄改變的時間

os.path.getmtime ('filename')     ##最後一次文件或目錄修改的時間

os.path.getsize('filename')       ##文件的大小

 wKioL1ls5uSAapzmAAB10C5p89k960.png-wh_50

 

 

文件測試相關:

os.path.isabs

os.path.isdir        ##判斷是不是一個目錄

os.path.isfile       ##判斷是不是一個文件

os.path.islink       ##判斷是不是一個連接

 

練習:找出用戶給定目錄下的全部以.log結尾的文件

 

import os

dir=raw_input('directory')

filelist=os.listdir(dir)

for file in filelist:

    if file.endswith('.log'):

        with open('logfile','a+') as f:

            a=os.path.join(dir,file)

            f.write(a)

            f.write('\n')

測試:

wKioL1ls5xDTf_xTAAA2rRIxsA4213.png-wh_50

wKiom1ls5xDzwO0uAAA5PmPCQ-E413.png-wh_50

 

 

 

 

              time 模塊

python中表示時間的三種方式:

1. 時間戳    time.time()

2. 格式化的時間字符串

3. 元組(共9個元素)  time.localtime()

 

 

time.mktime(t) 將元組格式時間轉化爲時間戳

time.localtime() 將時間戳轉化爲元組格式時間

time.sleep(secs)

time.ctime([secs]) 將時間戳轉化爲字符串格式顯示

time.strftime(format[,t]) 將元組格式時間轉化爲字符串顯示

time.strptime(string[,format]) 將字符串顯示轉化爲元組格式時間

wKioL1ls5ziA4p8HAAB3vjXbJhg582.png-wh_50

wKiom1ls5ziiXTDWAABjqZybD3Q542.png-wh_50

相關文章
相關標籤/搜索