歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python poll實現異步IO

Python poll實現異步IO

日期:2017/3/1 10:14:02   编辑:Linux編程

在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. def show_filesOfdir(whichDir):
  18. '''
  19. 此函數只顯示目錄下的所有文件
  20. using listdir() to shows all of the file execpt directory
  21. join() function catenate 'whichDir' with listdir() returns values
  22. isfile() check that file is a regular file
  23. '''
  24. #listdir() 函數顯示前目錄的內容
  25. for file in os.listdir(whichDir):
  26. #利用join()把whichDir目錄及listdir() 返回值連接起來組成合法路徑
  27. file_name = op.join(whichDir,file)
  28. #isfile()函數可以判斷該路徑上的文件是否為一個普通文件
  29. if op.isfile(file_name):
  30. print file_name


  31. def printaccess(path):
  32. '''
  33. 顯示文件的最後訪問時間,修改時間
  34. shows 'path' the last access time
  35. getatime() return the time of last access of path
  36. stat() return information of a file,use its st_atime return the time of last access
  37. ctime() return a string of local time
  38. '''
  39. import time
  40. #利用ctime()函數返回最後訪問時間
  41. #getatime()函數返回最後訪問時間,不過是以秒為單位(從新紀元起計算)
  42. print time.ctime(op.getatime(path))
  43. #stat()函數返回一個對象包含文件的信息
  44. stat = os.stat(path)
  45. #st_atime 最後一次訪問的時間
  46. print time.ctime(stat.st_atime)

  47. print the modify time
  48. print "modify time is:",
  49. print time.ctime(op.getctime(path))
  50. print "modify time is:",
  51. #st_ctime 最後一次修改的時間
  52. print time.ctime(stat.st_ctime)

  53. def isDIR(path):
  54. '''
  55. 一個os.path.isdir()函數的實現
  56. Implement isdir() function by myself

  57. '''
  58. import stat

  59. MODE = os.stat(path).st_mode
  60. #返回真假值
  61. return stat.S_ISDIR(MODE)


  62. if __name__== "__main__":

  63. change_dir()

  64. show_filesOfdir('''/root''')

  65. printaccess('/etc/passwd')
  66. print isDIR('/etc')
Copyright © Linux教程網 All Rights Reserved