How to open, read the file and save in a list of lists the contents of the file using Python

Asked

Viewed 1,939 times

1

I have a list of paths txt files.

With the read() function, I can save the entire contents of the file within a list where each word is stored at a list position. However as I intend to read 3 files at once and save the contents of each file in a list, I thought of saving these 3 generated lists of the respective 3 files in a list of lists. It would be something like this I’m trying to sketch:

lista_nome_base_docs = ['a.txt', 'b.txt', 'c.txt']
tamanho_lista_base_docs = len(lista_nome_base_docs)
print (tamanho_lista_base_docs)

lista_string_arquivos = [[]]

for i in range(3):
    with open(lista_nome_base_docs[i],"r") as arquivo:
    lista_string_arquivos.append(arquivo.read())

print (lista_string_arquivos)

I’m trying to save the contents of each file on a list of lists... would someone give me an idea of how to solve this?

at the end when I order printar, it is coming out totally strange this list of lists:

[[], '€\x03]q\x00]q\x01a.', '€\x03]q\x00]q\x01a.', '€\x03]q\x00]q\x01a.']

1 answer

2


First, you can open all 3 files simultaneously using the with , thus:

with open('a.txt') as a, open('b.txt') as b, open('c.txt') as c:
    #faca_algo_aqui

Then you can use the method .readlines() to return a list of each file by separating each row into a list item.

conteudo_a = a.readlines()
conteudo_b = b.readlines()
conteudo_c = c.readlines()

And after that put them all together in a general list:

conteudo_geral = []
for conteudo in [conteudo_a,conteudo_b,conteudo_c]:
    conteudo_geral.append(conteudo)

And finally your script would look like this:

lista_geral = []

with open('a.txt') as a, open('b.txt') as b, open('c.txt') as c:
    conteudo_a = a.readlines()
    conteudo_b = b.readlines()
    conteudo_c = c.readlines()

    for conteudo in [conteudo_a, conteudo_b, conteudo_c]:
        lista_geral.append(conteudo)
  • legal bro... but I thought of the for because the idea is from the archive of input.txt have a database of other files, one on each line, then check how many lines has the entree and would loop around, because the amount of files inside the entree may vary... you know what I mean?

  • I got bro doing this way: tamanho = len(lista_nome_base_docs)
print (tamanho)

lista_geral_arquivos = []


for i in range(tamanho):
 with open(lista_nome_base_docs[i],"r") as arquivo:
 conteudo = arquivo.readlines()
 lista_geral_arquivos.append(conteudo)

print (lista_geral_arquivos)

  • Ahh I get it. It’s just that you talked about reading the files at once, so I made the code following that recommendation, and the with passing the 3 at once would solve.. But since I wanted to read one and use it as the input of another the code would be another. But I’m glad that solved.

Browser other questions tagged

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