简体   繁体   中英

Python: output for recursively printing out files and folders

I have written a python 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM