[英]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). 我编写了一个python函数,该函数以递归方式打印出文件和文件夹,但是现在我不确定如何以美观的方式(以纯文本格式)显示它。 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: 那么您可以使用
pprint.pformat
创建可pprint.pformat
字符串表示形式:
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? 您在寻找纯文本的命令行显示还是在GUI中?
For command-line display, just use a recursive function passing an "indentation" variable to recursive calls, increasing it for each level: 对于命令行显示,只需使用递归函数,它将“ indentation”变量传递给递归调用,并在每个级别将其增加:
toplevel/
level2/
file.txt
file2.txt
level2_again/
file3.txt
For a GUI - use a widget provided by the relevant framework. 对于GUI-使用相关框架提供的小部件。 For example, with
PyQt
there's the QTreeView
widget. 例如,使用
PyQt
有QTreeView
小部件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.