jef*_*f_h 0 python recursion for-loop python-2.7
我正在尝试编写一个 python2 函数,该函数将递归遍历给定目录的整个目录结构,并打印出结果。
全部不使用 os.walk
这是我到目前为止所得到的:
test_path = "/home/user/Developer/test"
def scanning(sPath):
output = os.path.join(sPath, 'output')
if os.path.exists(output):
with open(output) as file1:
for line in file1:
if line.startswith('Final value:'):
print line
else:
for name in os.listdir(sPath):
path = os.path.join(sPath, name)
if os.path.isdir(path):
print "'", name, "'"
print_directory_contents(path)
scanning(test_path)
Run Code Online (Sandbox Code Playgroud)
这是我目前得到的,脚本没有进入新文件夹:
' test2'
'new_folder'
Run Code Online (Sandbox Code Playgroud)
问题是它不会比一个目录更深入。我还希望能够直观地指出什么是目录,什么是文件
小智 5
尝试这个:
import os
test_path = "YOUR_DIRECTORY"
def print_directory_contents(dir_path):
for child in os.listdir(dir_path):
path = os.path.join(dir_path, child)
if os.path.isdir(path):
print("FOLDER: " + "\t" + path)
print_directory_contents(path)
else:
print("FILE: " + "\t" + path)
print_directory_contents(test_path)
Run Code Online (Sandbox Code Playgroud)
我在 windows 上工作过,验证是否还在 unix 上工作。改编自:http : //codegists.com/snippet/python/print_directory_contentspy_skobnikoff_python