列出路径中的所有目录,并将信息保存到文本文件中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了列出路径中的所有目录,并将信息保存到文本文件中相关的知识,希望对你有一定的参考价值。

  1. ####################################################
  2. ##
  3. ## Prints a dir structure to a text file
  4. ##
  5. ## Usage : python printdir.py [path ala z:/mypath or /mypath/foo
  6. ##
  7. ####################################################
  8.  
  9. import os, sys
  10.  
  11. dir = sys.argv[1]
  12. outName = 'dirpaths.txt'
  13. f = open(outName,'w')
  14.  
  15. # write initial dir for reference
  16. f.write (dir + ' ')
  17.  
  18. count = 0
  19.  
  20. for item in os.walk(dir):
  21. count = count + 1
  22. item = item[0].replace('\','/')
  23. curPath = item.split('/')
  24. if count == 1:
  25. curPath = item
  26. else:
  27. curPath = ' ' * (len(curPath)-1) + curPath[len(curPath)-1]
  28.  
  29. f.write(curPath + ' ')
  30. print curPath
  31.  
  32.  
  33. f.close
  34. if os.path.exists(outName) :
  35. print 'File saved to: %s' % (outName)

以上是关于列出路径中的所有目录,并将信息保存到文本文件中的主要内容,如果未能解决你的问题,请参考以下文章