積累一些常用的子產品,可以讓我們在寫程式的時候事半功倍,下面記錄一下os.path子產品的一些常用函數及用法。
os.path子產品
basename('檔案路徑') 去掉目錄路徑,傳回fname檔案名
>>> os.path.basename('/home/addam/aa/test.txt')
'test.txt'
dirname('檔案路徑') 去掉檔案名,傳回目錄路徑
>>> os.path.dirname('/home/addam/aa/test.txt')
'/home/addam/aa'
join()将分離的各部分組合成一個路徑名
>>> os.path.join('/addam','test.txt')
'/addam/test.txt'
split()
分割檔案名與路徑;傳回(fpath,fname)元組;如果完全使用目錄,它也會将最後一個目錄作為檔案名分離,且不會判斷檔案或者目錄是否存在
>>> os.path.split('/home/addam/aa/test.txt')
('/home/addam/aa', 'test.txt')
os.path.splitext(“檔案路徑”) 分離檔案名與擴充名;預設傳回(fname,fextension)元組,可做分片操作>>> os.path.splitext('/home/addam/aa/test.txt')
('/home/addam/aa/test', '.txt')
>>> os.path.splitext('/home/addam/aa/test.txt')[0]
'/home/addam/aa/test'
>>> os.path.splitext('/home/addam/aa/test.txt')[1]
'.txt'
查詢函數:主要是判斷真假
exists() 指定路徑(檔案或者目錄)是否存在
>>> os.path.exists('/home/addam/')
True>>> os.path.exists('/home/addam/aa/test.txt')
True
>>> os.path.exists('/home/addam/')
True
>>> os.path.exists('/home/addam/test')
False
isabs() 指定路徑是否為絕對路徑
>>> os.path.isabs('/home/addam/')
True
isfile() 指定的路徑是否為一個檔案
>>> os.path.isfile('/home/addam/aa/test.txt')
True
>>> os.path.isfile('/home/addam/aa')
False
samefile() 兩個路徑名是否指向同一個檔案
查詢檔案資訊:
getatime() 傳回最近通路時間 (浮點型秒數)
>>> os.path.getatime('/home/addam')
1397222714.6862574
這種時間戳格式的時間看起來太别扭了,怎麼辦呢?轉換一下吧,利用python自帶的time子產品
>>> time.strftime('%Y_%m_%d %H:%M:%S',time.localtime(os.path.getatime('/home/addam/aa/test.txt')))
'2014_04_11 21:30:30'
getctime() 傳回檔案建立時間
>>> time.strftime('%Y_%m_%d %H:%M:%S',time.localtime(os.path.getctime('/home/addam/aa/test.txt')))
'2014_04_11 21:25:25
>>> os.path.getctime('/home/addam')
1397222712.2982574
getmtime() 傳回最近檔案修改時間
>>> time.strftime('%Y_%m_%d %H:%M:%S',time.localtime(os.path.getctime('/home/addam/')))
'2014_04_11 21:25:12'
>>> os.path.getmtime('/home/addam')
1397222712.2982574