开发者

Python: output for recursively printing out files and folders

I have written a pyt开发者_JAVA技巧hon function that recursively prints out files and folders, but now I am not sure how to display it in an aesthetic manner (in plain text). How do you display your folder structures?


If you write a function to return the directory structure as a nested list like this:

['DIR1/',['fileA','fileB','DIR3/',['fileE','fileF']],'DIR2/',['fileC','fileD']]

then you could use pprint.pformat to create a passable string representation:

import pprint
import textwrap
import re

data=['DIR1/',['fileA','fileB','DIR3/',['fileE','fileF']],'DIR2/',['fileC','fileD']]
print(textwrap.dedent(re.sub(r"[\]\[',]", r' ',
                             pprint.pformat(data,indent=4,width=1))))

yields

DIR1/  
    fileA  
    fileB  
    DIR3/  
        fileE  
        fileF    
DIR2/  
    fileC  
    fileD   

Note: The above code assumes your file and directory names do not contain any of the characters ,[]'...


Are you looking for a text-only command-line display or in a GUI?

For command-line display, just use a recursive function passing an "indentation" variable to recursive calls, increasing it for each level:

toplevel/
   level2/
      file.txt
      file2.txt
   level2_again/
      file3.txt

For a GUI - use a widget provided by the relevant framework. For example, with PyQt there's the QTreeView widget.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜