Chinaunix首页 | 论坛 | 博客

分类: Python/Ruby

2014-02-21 20:22:11

原文地址:Python os.stat 模块 作者:qidunhu


  1. #!/usr/bin/env python
  2. #-*- encoding:UTF-8 -*-
  3. import os,time,stat
  4. fileStats = os.stat ( 'test.txt' ) #获取文件/目录的状态
  5. fileInfo = {
  6. 'Size':fileStats [ stat.ST_SIZE ], #获取文件大小
  7. 'LastModified':time.ctime( fileStats [ stat.ST_MTIME ] ), #获取文件最后修改时间
  8. 'LastAccessed':time.ctime( fileStats [ stat.ST_ATIME ] ), #获取文件最后访问时间
  9. 'CreationTime':time.ctime( fileStats [ stat.ST_CTIME ] ), #获取文件创建时间
  10. 'Mode':fileStats [ stat.ST_MODE ] #获取文件的模式
  11. }
  12. #print fileInfo
  13. for field in fileInfo: #显示对象内容
  14.   print '%s:%s' % (field,fileInfo[field])
  15. for infoField,infoValue in fileInfo:
  16.   print '%s:%s' % (infoField,infoValue)
  17. if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ): #判断是否路径
  18.   print 'Directory. '
  19. else:
  20.   print 'Non-directory.'
  21. if stat.S_ISREG( fileStats [ stat.ST_MODE ] ): #判断是否一般文件
  22.    print 'Regular file.'
  23. elif stat.S_ISLNK ( fileStats [ stat.ST_MODE ] ): #判断是否链接文件
  24.    print 'Shortcut.'
  25. elif stat.S_ISSOCK ( fileStats [ stat.ST_MODE ] ): #判断是否套接字文件
  26.    print 'Socket.'
  27. elif stat.S_ISFIFO ( fileStats [ stat.ST_MODE ] ): #判断是否命名管道
  28.    print 'Named pipe.'
  29. elif stat.S_ISBLK ( fileStats [ stat.ST_MODE ] ): #判断是否块设备
  30.    print 'Block special device.'
  31. elif stat.S_ISCHR ( fileStats [ stat.ST_MODE ] ): #判断是否字符设置
  32.    print 'Character special device.'
  33.    stat模块描述了os.stat(filename)返回的文件属性列表中各值的意义.我们可方便地根据stat模块存取os.stat()中的值.
  34. 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(创建的时间)
  35. >>> import os
  36. >>> print os.stat("/root/python/zip.py")
  37. (33188, 2033080, 26626L, 1, 0, 0, 864, 1297653596, 1275528102, 1292892895)
  38. >>> print os.stat("/root/python/zip.py").st_mode #权限模式
  39. 33188
  40. >>> print os.stat("/root/python/zip.py").st_ino #inode number
  41. 2033080
  42. >>> print os.stat("/root/python/zip.py").st_dev #device
  43. 26626
  44. >>> print os.stat("/root/python/zip.py").st_nlink #number of hard links
  45. 1
  46. >>> print os.stat("/root/python/zip.py").st_uid #所有用户的user id
  47. 0
  48. >>> print os.stat("/root/python/zip.py").st_gid #所有用户的group id
  49. 0
  50. >>> print os.stat("/root/python/zip.py").st_size #文件的大小,以位为单位
  51. 864
  52. >>> print os.stat("/root/python/zip.py").st_atime #文件最后访问时间
  53. 1297653596
  54. >>> print os.stat("/root/python/zip.py").st_mtime #文件最后修改时间
  55. 1275528102
  56. >>> print os.stat("/root/python/zip.py").st_ctime #文件创建时间
  57. 1292892895

阅读(1353) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~