A
A
ArtemZA2017-10-16 16:18:51
Python
ArtemZA, 2017-10-16 16:18:51

How to do depth traversal based on file system?

Hello. I'm trying to implement a depth-first graph traversal based on the file system, but it doesn't work.
Count from folders
59e4b8cf533c8501482951.jpeg

import glob
import os
import codecs
import time

node = {}
spisok = []
visited = []

def filegraph(start, last ):
    if start not in visited:
        spisok.clear()
        names = os.listdir(start)
        visited.append(start)
        
       #print(visited)
        print(start , ' Текущая директория')
        #print(os.getcwd())
        print(last , ' Последняя директория')
        
        for name in names:
            directory = os.path.join(start, name)            
            if os.path.isdir(directory) == True:
                spisok.append(directory)
                print(directory , 'директория')
        print( spisok ,  ' список')
        
        print(last)
        node[start] = last , spisok #Добавляем в словарь
        try:
            print(node[last] , ' last' )
        except KeyError:
            print(' Ключа нет')
        print(node[start] , ' start')
        #print(node ,  ' node')
        if len(spisok) != 0:
            for a in range(0 , len(spisok)):
                if node[start][1][a] not in visited:
                    
                    time.sleep(3)
                    os.chdir(node[start][1][a])
                    for key in node:
                        print('%s -> %s' % (key , node[key]) , end = ' \n')
                    print(node[start][1][a] , ' start ' , '-' * 10 )
                    return filegraph(node[start][1][a] ,start)
                
        else:
            time.sleep(3)
            print(' Возвращение ' )
            print(node[start][0] , ' start  0' )
            for key in node:
                print('%s -> %s' % (key , node[key]) , end = ' \n')

            return filegraph(node[start][0] , '')
    elif start in visited:
        print( visited , ' visited')
        print(node)
        for key in node:
                print('%s -> %s' % (key , node[key]) , end = ' \n')
        print(start , ' Посещено')
        #print(node[u'D:\\Project\\test\\First '])



filegraph(u"D:\\Project\\test" , '' )

What was achieved:
The algorithm only reaches the end of one branch
. What is wrong:
I am trying to store vertices in a dictionary, but I noticed that almost from the very beginning the dictionary is overwritten and returning to a higher level thanks to the dictionary does not work.
D:\Project\test  Текущая директория
  Последняя директория
D:\Project\test\First директория
D:\Project\test\Second директория
D:\Project\test\Three директория
['D:\\Project\\test\\First', 'D:\\Project\\test\\Second', 'D:\\Project\\test\\Three']  список

 Ключа нет
('', ['D:\\Project\\test\\First', 'D:\\Project\\test\\Second', 'D:\\Project\\test\\Three'])  start
D:\Project\test -> ('', ['D:\\Project\\test\\First', 'D:\\Project\\test\\Second', 'D:\\Project\\test\\Three']) 
D:\Project\test\First  start  ----------
D:\Project\test\First  Текущая директория
D:\Project\test  Последняя директория
D:\Project\test\First\1-2 директория
['D:\\Project\\test\\First\\1-2']  список
D:\Project\test
('', ['D:\\Project\\test\\First\\1-2'])  last
('D:\\Project\\test', ['D:\\Project\\test\\First\\1-2'])  start
D:\Project\test -> ('', ['D:\\Project\\test\\First\\1-2']) 
D:\Project\test\First -> ('D:\\Project\\test', ['D:\\Project\\test\\First\\1-2']) 
D:\Project\test\First\1-2  start  ----------

Please tell me what can be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tsarevfs, 2017-10-16
@ArtemZA

Для реальной задачи используйте os.walk.
Пробел после запятой -- зло!

def filegraph(current, last):
    
    if current in visited:
        print( visited, ' visited')
        print(node)
        for key in node:
                print('%s -> %s' % (key, node[key]), end = ' \n')
        print(current, ' Посещено')
        return #*Сразу выходим, чтобы уменьшить вложенность кода*

    #spisok.clear()
    current_dir_items = [] #*это список файлов в текущей директории, то что он был глобальным создавало проблемы ниже*

    names = os.listdir(current)
    visited.append(current)
    
    print(current, ' Текущая директория')
    print(last, ' Последняя директория')
    
    for name in names:
        directory = os.path.join(current, name)            
        if os.path.isdir(directory) == True:
            current_dir_items.append(directory)
            print(directory, 'директория')
    print( current_dir_items,  ' список')
    
    print(last)
    node[current] = last, current_dir_items #Добавляем в словарь !!!список не копируется, мы помещаем в словарь ссылку на него!!!
    
    if (last in node) #*логика на исключениях -- плохая идея*
        print(node[last], ' last' )
    else
        print(' Ключа нет')

    print(node[current], ' current')
    if len(current_dir_items) != 0:
        #for a in range(0, len(current_dir_items)):
        #    if node[current][1][a] not in visited:
        for next_item in current_dir_items: #*по возможности не используйте for in range(len)*
            if next_item not in visited: 
                time.sleep(3) 
                os.chdir(next_item) #*код становится проще*
                for key in node:
                    print('%s -> %s' % (key, node[key]), end = ' \n')
                print(next_item, ' current ', '-' * 10 )
                return filegraph(next_item, current) #тут происходил spisok.clear() и портил вам данные в словаре. 
            
    else:
        time.sleep(3)
        print(' Возвращение ' )
        print(node[current][0], ' current  0' )
        for key in node:
            print('%s -> %s' % (key, node[key]), end = ' \n')

        return filegraph(node[current][0], '')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question