Python poll实现异步IO


在python中对文件及目录的操作一般涉及多os模块,os.path模块。具体函数以及使用方法在程序中说明。

  1. #!/usr/bin/env python
  2. #-*- coding=UTF8 -*-

  3. import os

  4. import os.path as op

  5. def change_dir():
  6.     '''
  7.   该函数显示及改变前目录
  8. using chdir() to change current dir
  9.         getcwd() can show the current working directory
  10.     '''
  11.     directory="/tmp"
  12.     #使用getcwd()返回当前目录
  13.     print os.getcwd()
  14.     #chdir改变当前目录为:directory目录
  15.     os.chdir(directory)
  16.     print os.getcwd()
  17.     
  18. def show_filesOfdir(whichDir):
  19.     '''
  20. 此函数只显示目录下的所有文件
  21.  using listdir() to shows all of the file execpt directory
  22.       join() function catenate 'whichDir' with listdir() returns values
  23.      isfile() check that file is a regular file
  24.      '''    
  25.      #listdir() 函数显示前目录的内容
  26.     for file in os.listdir(whichDir):
  27. #利用join()把whichDir目录及listdir() 返回值连接起来组成合法路径
  28.         file_name = op.join(whichDir,file)
  29. #isfile()函数可以判断该路径上的文件是否为一个普通文件
  30.         if op.isfile(file_name):
  31.             print file_name


  32. def printaccess(path):
  33.     ''
  34. 显示文件的最后访问时间,修改时间
  35. shows 'path' the last access time
  36.             getatime() return the time of last access of path
  37.      stat() return information of a file,use its st_atime return the time of last access
  38.      ctime() return a string of local time
  39.     '''
  40.     import time
  41.     #利用ctime()函数返回最后访问时间
  42.     #getatime()函数返回最后访问时间,不过是以秒为单位(从新纪元起计算)
  43.     print time.ctime(op.getatime(path))
  44.     #stat()函数返回一个对象包含文件的信息
  45.     stat = os.stat(path)
  46.     #st_atime 最后一次访问的时间
  47.     print time.ctime(stat.st_atime)

  48.     print the modify time
  49.     print "modify time is:",
  50.     print time.ctime(op.getctime(path))
  51.     print "modify time is:",
  52.     #st_ctime 最后一次修改的时间
  53.     print time.ctime(stat.st_ctime)

  54. def isDIR(path):
  55.     '''
  56. 一个os.path.isdir()函数的实现
  57.  Implement isdir() function by myself
  58.     
  59.     '''
  60.     import stat

  61.     MODE = os.stat(path).st_mode
  62.     #返回真假值
  63.     return stat.S_ISDIR(MODE)
  64.     
  65.     
  66. if __name__== "__main__":
  67.     
  68.     change_dir()

  69.     show_filesOfdir('''/root''')

  70.     printaccess('/etc/passwd')
  71.     print isDIR('/etc')

相关内容