Python 的 stat 模块

 1 #!/usr/bin/env python
 2 #-*- encoding:UTF-8 -*-
 3 
 4 import os,time,stat
 5 
 6 fileStats = os.stat ( 'test.txt' )                         #获取文件/目录的状态
 7 fileInfo = {
 8 'Size':fileStats [ stat.ST_SIZE ],                         #获取文件大小
 9 'LastModified':time.ctime( fileStats [ stat.ST_MTIME ] ),  #获取文件最后修改时间
10 'LastAccessed':time.ctime( fileStats [ stat.ST_ATIME ] ),  #获取文件最后访问时间
11 'CreationTime':time.ctime( fileStats [ stat.ST_CTIME ] ),  #获取文件创建时间
12 'Mode':fileStats [ stat.ST_MODE ]                          #获取文件的模式
13 }
14 #print fileInfo
15 
16 for field in fileInfo:                                     #显示对象内容
17   print '%s:%s' % (field,fileInfo[field])
18 
19 for infoField,infoValue in fileInfo:
20   print '%s:%s' % (infoField,infoValue)
21 if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):           #判断是否路径
22   print 'Directory. '
23 else:
24   print 'Non-directory.'
25 
26 if stat.S_ISREG( fileStats [ stat.ST_MODE ] ):           #判断是否一般文件
27    print 'Regular file.'
28 elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ):         #判断是否链接文件
29    print 'Shortcut.'
30 elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ):        #判断是否套接字文件    
31    print 'Socket.'
32 elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ):        #判断是否命名管道
33    print 'Named pipe.'
34 elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ):         #判断是否块设备
35    print 'Block special device.'
36 elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ):         #判断是否字符设置
37    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

附:本文摘自 http://www.cnblogs.com/gaitian00/p/4034540.html

posted @ 2014-12-17 13:14  colben  阅读(239)  评论(0)    收藏  举报