gpt4 book ai didi

python - Python中递归打印文件目录

转载 作者:太空宇宙 更新时间:2023-11-03 18:30:50 27 4
gpt4 key购买 nike

我试图弄清楚如何以正确的缩进打印目录中的每个项目。到目前为止我的代码如下:

import os

def traverse(pathname,d):
'prints a given nested directory with proper indentation'
indent = ''
for i in range(d):
indent = indent + ' '
for item in os.listdir(pathname):
try:
newItem = os.path.join(pathname, item)
traverse(newItem,d+1)
except:
print(indent + newItem)

我的输出打印出测试目录中的所有文件,但不打印文件夹名称。我得到的是这样的:

>>> traverse('test',0)
test/fileA.txt
test/folder1/fileB.txt
test/folder1/fileC.txt
test/folder1/folder11/fileD.txt
test/folder2/fileD.txt
test/folder2/fileE.txt
>>>

输出应该是什么:

>>> traverse('test',0)
test/fileA.txt
test/folder1
test/folder1/fileB.txt
test/folder1/fileC.txt
test/folder1/folder11
test/folder1/folder11/fileD.txt
test/folder2
test/folder2/fileD.txt
test/folder2/fileE.txt
>>>

谁能让我知道我需要用代码做什么才能显示文件夹名称?我尝试打印出路径名,但每次 Python 打印出文件名时,它都会重复文件夹名称,因为它处于 for 循环中。如果能朝正确的方向插入,我们将不胜感激!

最佳答案

无论是否是目录,您都需要打印文件名,例如:

for item in os.listdir(pathname):
try:
newItem = os.path.join(pathname, item)
print(indent + newItem)
traverse(newItem,d+1)
except:
pass

虽然我不想使用异常来检测它是否是一个目录,所以如果允许os.path.isdir:

for item in os.listdir(pathname):
newItem = os.path.join(pathname, item)
print(indent + newItem)
if (os.path.isdir(newItem)):
traverse(newItem,d+1)

关于python - Python中递归打印文件目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22411576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com