目录和子目录

我正在编写一个程序,它应该在特定目录中进行越来越深入的研究。如果当前目录的元素是文件,请写下它们的名称。否则-深入它们,从更深的目录中写出文件。我就快解决了,问题是--我不知道该怎么告诉Python去做:
如果目录为空,则传递它。

# 回答1


使用os.walk递归访问某个目录下的子目录和文件。在下面的代码中,消息
"目录%s\n"%(根)中没有文件
如果子目录为空,则显示。

选择 | 换行 | 行号
  1. import os
  2.  
  3. dir_name = (os.path.join('D:/', 'SDS2_7.0', 'macro', 'Defaults'))
  4.  
  5. a = os.walk(dir_name)
  6.  
  7. for root, dir, file in a:
  8.  
  9.     print "Root directory: %s" % (root)
  10.  
  11.     if dir:
  12.         print "Subdirectories under %s:" % (root)
  13.         dirList = map(lambda x: '%s\n' % (x), dir)
  14.         dirStr = "".join(dirList)
  15.         print dirStr
  16.     else:
  17.         print "There are no subdirectories under directory %s\n" % (root)
  18.  
  19.     if file:
  20.         print "Files in directory %s:" % (root)
  21.         fileList = map(lambda x: '%s\n' % (os.path.join(root, x)), file)
  22.         fileStr = "".join(fileList)
  23.         print fileStr
  24.     else:
  25.         print "There are no files in directory %s\n" % (root)

标签: python

添加新评论