获取给定目录中子目录的列表

2024-04-25 19:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在获取列出给定目录中所有目录/子目录的xml结构时遇到了困难。我在given post中使用递归来工作,我的问题比平常要难一点。我的目录中可能有10000个文件,所以检查每一个内容,看它是否是一个目录,这将是昂贵的,它已经花了很长时间来构建xml。我只想为目录构建xml。在

我知道linux有一些命令,比如find。-键入d列出存在的目录(而不是文件)。如何在python中实现这一点呢。在

提前谢谢。在


Tags: 文件命令目录内容键入linuxxmlfind
3条回答

^{}已经区分了文件和目录:

def find_all_dirs(root='.'):
    for path,dirs,files in os.walk(root):
        for d in dirs:
            yield os.path.join(path, d)

只有一个目录。。。在

import os

def get_dirs(p):
  p = os.path.abspath(p)
  return [n for n in os.listdir(p) if os.path.isdir(os.path.join(p, n))]

print "\n".join(get_dirs("."))

这是我在寻找和尝试不同事物后得到的解决方案。我并不是说这种查找目录中每一个内容的方法要快得多,但它实际上产生的结果要快得多(当目录包含1000个文件时,差异是可见的)

import os
import subprocess
from xml.sax.saxutils import quoteattr as xml_quoteattr

def DirAsLessXML(path):

    result = '<dir type ={0} name={1} path={2}>\n'.format(xml_quoteattr('dir'),xml_quoteattr(os.path.basename(path)),xml_quoteattr(path))

    list = subprocess.Popen(['find', path,'-maxdepth', '1', '-type', 'd'],stdout=subprocess.PIPE, shell=False).communicate()[0]

    output_list = list.splitlines()
    if len(output_list) == 1:
        result = '<dir type ={0} name={1} path={2}>\n'.format(xml_quoteattr('leaf_dir'),xml_quoteattr(os.path.basename(path)),xml_quoteattr(path))

    for item in output_list[1:]:
        result += '\n'.join('  ' + line for line in DirAsLessXML(item).split('\n'))
    result += '</dir>\n'
    return result

相关问题 更多 >