列出目录中的所有序列(递归)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了列出目录中的所有序列(递归)相关的知识,希望对你有一定的参考价值。

Loads of code lifted from here :
http://www.tokeru.com/t/bin/view/Maya/MayaPython#ListDir
  1. import os, sys
  2. #from sets import Set
  3. path = 'Z:/job/TOTEM/SHOTS/AZ003/Frames/render/character/'
  4. files = os.listdir(path)
  5.  
  6. finalSeqList = []
  7.  
  8. def padFrame(frame,pad):
  9. return '0' * (pad - len(str(frame))) + str(frame)
  10.  
  11. def seqLS (dirPath):
  12. files = os.listdir(dirPath)
  13. for file in files:
  14. try:
  15. prefix, frame, suffix = file.split('.')
  16.  
  17. # build a dictionary of the sequences as {name: frames, suffix}
  18. #
  19. # eg beauty.01.tif ... beauty.99.tif will convert to
  20. # { beauty : [01,02,...,98,99], tif }
  21.  
  22. try:
  23. result[prefix][0].append(frame)
  24. except KeyError:
  25. # we have a new file sequence, so create a new key:value pair
  26. result[prefix] = [[frame],suffix]
  27. except ValueError:
  28. # the file isn't in a sequence, add a dummy key:value pair
  29. result[file] = file
  30.  
  31.  
  32. for prefix in result:
  33. if result[prefix] != prefix:
  34. frames = result[prefix][0]
  35. frames.sort()
  36.  
  37. # find gaps in sequence
  38. startFrame = int(frames[0])
  39. endFrame = int(frames[-1])
  40. pad = len(frames[0])
  41. idealRange = set(range(startFrame,endFrame))
  42. realFrames = set([int(x) for x in frames])
  43. # sets can't be sorted, so cast to a list here
  44. missingFrames = list(idealRange - realFrames)
  45. missingFrames.sort()
  46.  
  47. #calculate fancy ranges
  48. subRanges = []
  49. for gap in missingFrames:
  50. if startFrame != gap:
  51. rangeStart = padFrame(startFrame,pad)
  52. rangeEnd = padFrame(gap-1,pad)
  53. subRanges.append('-'.join([rangeStart, rangeEnd]))
  54. startFrame = gap+1
  55.  
  56. subRanges.append('-'.join([padFrame(startFrame,pad), padFrame(endFrame,pad) ]))
  57. frameRanges = ','.join(subRanges)
  58. frameRanges = '[%s]' % (frameRanges)
  59. suffix = result[prefix][1]
  60. sortedList.append('.'.join([prefix, frameRanges ,suffix]))
  61. print (' ' + '.'.join([prefix, frameRanges ,suffix]))
  62. else: sortedList.append(prefix)
  63.  
  64.  
  65. if __name__ == '__main__':
  66. if len(sys.argv) > 1:
  67. path = sys.argv[1]
  68.  
  69. for root, dirs, files in os.walk(path):
  70. for curDir in dirs:
  71. fulldir = os.path.join(root, curDir)
  72. print 'Scanning : %s' % (fulldir)
  73. result = {}
  74. sortedList = []
  75. seqLS(fulldir)

以上是关于列出目录中的所有序列(递归)的主要内容,如果未能解决你的问题,请参考以下文章

递归法列出目录中的所有文件

在Unix中递归列出文件中的所有文件? [复制]

PHP - 在下拉菜单中递归列出所有目录和子目录[重复]

在 zipfile 中递归列出所有目录而不在 python 中提取

递归控制-列出所有组合

以编程方式递归列出eclipse工作区中的所有文件