Python正则表达式打印目录列表

2024-10-01 07:25:49 发布

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

在python中,我有一个目录列表,其中包含以下数据:

/a
/a/b
/a/b/1
/a/b/2
/a/b/3
/a/c
/a/c/1
/a/c/2
/a/c/3
/a/d
/a/d/1
/a/d/2
/f
/f/g
/f/g/h
/f/g/i
/f/g/j

我希望以以下格式显示输出:

/a
    /b
        /1
        /2
        /3
    /c
        /1
        /2
        /3
    /d
        /1
        /2
/f
    /g
        /h
        /i
        /j

我正在使用以下python函数,但它正在打印不一致的输出:

def formatVFS(lst):
    for line in lst:
        l1 = list(lst)
        l2 = []
        if re.search(r'^/\w+', line) != None:
            temp = re.search(r'^/\w+', line).group()
            print '\t\t', temp
            for line2 in l1:
                if line2.startswith(temp):
                    lst.remove(line2)
                    line2 = line2.replace(temp, '')
                    if line2!= '':
                        l2.append(line2)
                        print '\t\t\t',line2
            formatVFS(l2)

有什么建议吗


Tags: inre目录l1列表forsearchif
1条回答
网友
1楼 · 发布于 2024-10-01 07:25:49

请尝试下面的程序,该程序将搜索并替换不在行尾的\/\w+,并使用制表符。假设文件夹按预期顺序排列。如果没有,可以在显示之前对其进行排序

import re
l=["/a","/a/b","/a/b/1","/a/b/2","/a/b/3","/a/c","/a/c/1","/a/c/2","/a/c/3","/a/d","/a/d/1","/a/d/2","/f","/f/g","/f/g/h","/f/g/i","/f/g/j"]
for i in l:
    print(re.sub(r"\/\w+(?=\/(?!$))","\t",i))

输出

/a
        /b
                /1
                /2
                /3
        /c
                /1
                /2
                /3
        /d
                /1
                /2
/f
        /g
                /h
                /i
                /j

相关问题 更多 >