[英]traverse directory structure in python recursively without os.walk
我正在嘗試編寫一個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)
這是我當前得到的,腳本不會進入新文件夾:
' test2'
'new_folder'
問題在於,它不會比一個目錄更深入。 我還希望能夠直觀地指示什么是目錄,什么是文件
嘗試這個:
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)
我在Windows上工作,請驗證是否仍在UNIX上工作。 改編自: http : //codegists.com/snippet/python/print_directory_contentspy_skobnikoff_python
遞歸嘗試一下,它很簡單,代碼更少
import os
def getFiles(path="/var/log", files=[]):
if os.path.isfile(path):
return files.append(path)
for item in os.listdir(path):
item = os.path.join(path, item)
if os.path.isfile(item):
files.append(item)
else:
files = getFiles(item, files)
return files
for f in getFiles("/home/afouda/test", []):
print(f)
嘗試使用遞歸函數,
def lastline(fil):
with open(fil) as f:
for li in f.readlines():
if li.startswith("Final Value:"):
print(li)
## If it still doesnt work try putting 'dirs=[]' here
def lookforfiles(basepath):
contents = os.listdir(basepath)
dirs = []
i = 0
while i <= len(contents):
i += 1
for n in contents:
f = os.path.join(basepath, n)
if os.path.isfile(f):
lastline(f)
print("\n\nfile %s" % n)
elif os.path.isdir(f):
print("Adding dir")
if f in dirs:
pass
else:
dirs.append(f)
else:
for x in dirs:
print("dir %s" % x)
lookforfiles(x)
抱歉,如果這與您的示例不符,但我很難理解您要執行的操作。
這個問題是“ 打印出整個目錄樹”的副本。
TL; TR:使用os.listdir
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.