#!/usr/bin/env python
#-*- encoding:UTF-8 -*-
import os,time,stat
fileStats = os.stat ( 'test.txt' ) #獲取文件/目錄的狀態
fileInfo = {
'Size':fileStats [ stat.ST_SIZE ], #獲取文件大小
'LastModified':time.ctime( fileStats [ stat.ST_MTIME ] ), #獲取文件最后修改時間
'LastAccessed':time.ctime( fileStats [ stat.ST_ATIME ] ), #獲取文件最后訪問時間
'CreationTime':time.ctime( fileStats [ stat.ST_CTIME ] ), #獲取文件創建時間
'Mode':fileStats [ stat.ST_MODE ] #獲取文件的模式
}
#print fileInfo
for field in fileInfo: #顯示對象內容
print '%s:%s' % (field,fileInfo[field])
for infoField,infoValue in fileInfo:
print '%s:%s' % (infoField,infoValue)
if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): #判斷是否路徑
print 'Directory. '
else:
print 'Non-directory.'
if stat.S_ISREG( fileStats [ stat.ST_MODE ] ): #判斷是否一般文件
print 'Regular file.'
elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ): #判斷是否鏈接文件
print 'Shortcut.'
elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ): #判斷是否套接字文件
print 'Socket.'
elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ): #判斷是否命名管道
print 'Named pipe.'
elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ): #判斷是否塊設備
print 'Block special device.'
elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ): #判斷是否字符設置
print 'Character special device.'
stat模塊描述了os.stat(filename)返回的文件屬性列表中各值的意義.我們可方便地根據stat模塊存取os.stat()中的值.
os.stat(path)執行一個stat()系統調用在給定的path上,返回一個類元組對象(stat_result對象,包含10個元素),屬性與stat結構成員相關:st_mode(權限模式),st_ino(inode number),st_dev(device),st_nlink(number of hard links),st_uid(所有用戶的user id),st_gid(所有用戶的group id),st_size(文件大小,以位為單位),st_atime(最近訪問的時間),st_mtime(最近修改的時間),st_ctime(創建的時間)
>>> import os >>> print os.stat("/root/python/zip.py") (33188, 2033080, 26626L, 1, 0, 0, 864, 1297653596, 1275528102, 1292892895) >>> print os.stat("/root/python/zip.py").st_mode #權限模式 33188 >>> print os.stat("/root/python/zip.py").st_ino #inode number 2033080 >>> print os.stat("/root/python/zip.py").st_dev #device 26626 >>> print os.stat("/root/python/zip.py").st_nlink #number of hard links 1 >>> print os.stat("/root/python/zip.py").st_uid #所有用戶的user id 0 >>> print os.stat("/root/python/zip.py").st_gid #所有用戶的group id 0 >>> print os.stat("/root/python/zip.py").st_size #文件的大小,以位為單位 864 >>> print os.stat("/root/python/zip.py").st_atime #文件最后訪問時間 1297653596 >>> print os.stat("/root/python/zip.py").st_mtime #文件最后修改時間 1275528102 >>> print os.stat("/root/python/zip.py").st_ctime #文件創建時間 1292892895 |