Problems when creating lists

Asked

Viewed 51 times

0

I am trying to get the program to create a list with the name of the files found in the directory and within each entry of this list, create a list of strings with the contents found inside the files

I tried to go debugging the indices the way I knew and concluded that it works the first time I rotate the loop and then it doesn’t work anymore

'''

infos = [[]]
for fileFound in os.listdir('.'):
    for i in range(len(os.listdir('.'))):
        infos[i].append(fileFound)
        textFile = open(fileFound)
        infos[i].append(textFile.readlines())

'''

1 answer

1


Yan, it is possible to do this in two ways without opening another loop within the first "for", example:

1) Using the list (doc) The Dice is sequential numeric :

import os

infos = []

for fileFound in os.listdir('.'):
  if '.' in fileFound:
    nome_arquivo  = fileFound
    dados_arquivo = open(fileFound).read() 
    infos.append([nome_arquivo, dados_arquivo])

2) Using the dictionary (doc) the "Indice" can be the file name:

import os

infos = {}

for fileFound in os.listdir('.'):
  if '.' in fileFound:
    nome_arquivo  = fileFound
    dados_arquivo = open(fileFound).read() 
    infos[nome_arquivo] = dados_arquivo

Browser other questions tagged

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