Remove empty list in Python

Asked

Viewed 382 times

0

os.chdir(pasta)   
lista = []
 for air in os.walk('.'):
  if lista != []:
    lista.append(air)
     print(lista)

Could someone tell me why I can’t print the folders?

If I take the if, folders appears, but also appears [].

[('.', ['Game_play', 'Menu', 'Settings', 'Setup'], ['testes.json']), ('.\\Game_play', ['tc001.air', 'tc002.air', 'tc003.air'], []), ('.\\Game_play\\tc001.air', [], ['tc001.py']), ('.\\Game_play\\tc002.air', [], ['tc002.py']), ('.\\Game_play\\tc003.air', [], ['tc003.py']), ('.\\Menu', ['tc001.air'], []), ('.\\Menu\\tc001.air', [], ['tc001.py']), ('.\\Settings', ['tc001.air'], []), ('.\\Settings\\tc001.air', [], ['tc001.py']), ('.\\Setup', ['tc001.air'], []), ('.\\Setup\\tc001.air', [], ['tc001.py'])]

Process finished with exit code 0

I can’t print just the folders without those [] with nothing.

1 answer

3


It doesn’t work because the logic of your code is wrong.

The object lista begins with the value [], an empty list and only changes, that is, a new element is added if the condition if lista != [] is satisfied. This is almost paradoxical with its goal. By the way, why check whether the list in question is empty here?

The return of function os.walk is a tuple that holds the values: root, root directory of the structure in question, dirs, list of directories within root, file, list of files within root.

If the idea is just to list directories that have subdirectories, you’ll need to check that dirs, of the return of os.walk, is an empty list. Something like:

for air in os.walk('.'):
  if air[1]:
    lista.append(air)

If you are using Python 3.4 or higher, I recommend you study the module pathlib.

Browser other questions tagged

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