我正在编写一个程序,它应该在特定目录中进行越来越深入的研究。如果当前目录的元素是文件,请写下它们的名称。否则-深入它们,从更深的目录中写出文件。我就快解决了,问题是--我不知道该怎么告诉Python去做:
如果目录为空,则传递它。
# 回答1
使用os.walk递归访问某个目录下的子目录和文件。在下面的代码中,消息
"目录%s\n"%(根)中没有文件
如果子目录为空,则显示。
- import os
-
- dir_name = (os.path.join('D:/', 'SDS2_7.0', 'macro', 'Defaults'))
-
- a = os.walk(dir_name)
-
- for root, dir, file in a:
-
- print "Root directory: %s" % (root)
-
- if dir:
- print "Subdirectories under %s:" % (root)
- dirList = map(lambda x: '%s\n' % (x), dir)
- dirStr = "".join(dirList)
- print dirStr
- else:
- print "There are no subdirectories under directory %s\n" % (root)
-
- if file:
- print "Files in directory %s:" % (root)
- fileList = map(lambda x: '%s\n' % (os.path.join(root, x)), file)
- fileStr = "".join(fileList)
- print fileStr
- else:
- print "There are no files in directory %s\n" % (root)