List and Access Python subdirectories

Asked

Viewed 1,068 times

0

Good afternoon guys, I’m trying to create a very simple text file management system, but in some of the difficulties I am found is accessing and manipulating files in subdirectories. Below I have part of the code for folder handling.

I am able to access the main folder, but I can’t list files from the subfolders, nor access subfolders (and keep access in case I have a file I can edit the same)

My question is how I can access a subdirectory and keep it in access so I can edit something I have in it (or also access a folder inside this subdirectory) and when I finish, return to the main folder, and if I arrive in the main the program finish.

# -*- coding:utf-8 -*-

import os
import os.path
import shutil

caminhoPAI = '/Users/proce/Desktop/Explorer'


def title(tl):
    print('=' * 80)
    print(f'{tl:^80}'.upper())
    print('=' * 80)
    print()


def acess_dir(caminho):
    with os.scandir(caminho) as it:
        for entry in it:
            if not entry.name.startswith('.') and entry.is_dir():
                print('\t', entry.name)


def listar_arquivos(caminho):
    with os.scandir(caminho) as it:
        for entrar in it:
            if not entrar.name.startswith('.') and entrar.is_file():
                print('\t', entrar.name)


def menu_diretorios():
    title('Navegando pelo Menu DIRETÓRIOS')
    print('Escolha sua opção: ')
    op = str(input('''
        [mkdir] - Criar diretórios
        [rm] - Apagar diretórios
        [cd] - Acessar diretórios
        [ls] - Listar Arquivos
        [exit] - Retornar/Sair
        Opção: ''')).lower()

    if op == 'exit':
        exit(1)

# ------------------------------------------------------------------------------------------- #
    elif op == 'cd':  # ACESSAR DIRETORIOS
        print('_' * 40)
        acess_dir(caminhoPAI)
        tem = (str(input('Informe o nome da pasta a ser acessada: ')))
        dir_acesso = tem
        if not os.path.exists(dir_acesso):
            j = 'S'
            while j == 'S':
                j = str(input('Pasta inexistente. Deseja tentar outra? [S/N]')).upper()
        else:
            for caminho, pastas, arquivos in os.walk(caminhoPAI):
                for pasta in pastas[:]:
                    if pasta == dir_acesso:
                        caminho = tem
                        os.chdir(caminho)
                        print('Pasta acessada!')
        print('_' * 40)

        menu_diretorios()
# ------------------------------------------------------------------------------------------- #
    elif op == 'ls':  # LISTAR ARQUIVOS
        print(listar_arquivos(caminhoPAI))
        print(os.getcwd())
        menu_diretorios()

# ------------------------------------------------------------------------------------------- #
    else:
        print("Esta opção não está nas alternativas, tente novamente.\n")
        menu_diretorios()


print(menu_diretorios())

Thanks for all your help and support! Thank you.

1 answer

1

The command os.chdir() is changing the current python directory, however, when you will access it you are always using the variable caminhoPAI that is not being altered...

A (partial) solution would be to keep the variable instead of changing the directory caminhoPAI up-to-date:

caminhoPAI = caminho

However, thus you lose the reference of which initial folder from when the program started. You can work around this by using two variables, one for the initial path and a second variable by keeping the current path:

caminhoAtual = caminho

Use this variable caminhoAtual when it comes to calling their duties listarArquivos, instead of using the caminhoPAI that is fixed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.