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

1

I have a list with file.txt paths

With the read () function, I can save the entire contents of the file into a list where each word is stored in a list position. But since I intend to read 3 files at once and save the contents of each file in a list, I thought about saving those 3 generated lists of their 3 files in a list of lists. It would be something like this so I'm trying to sketch it:

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 in a list of lists ... could anyone give me an idea how to solve this?

At the end when I send printers, it's coming out totally strange is list of lists:

[[], '€\x03]q\x00]q\x01a.', '€\x03]q\x00]q\x01a.', '€\x03]q\x00]q\x01a.']
    
asked by anonymous 06.10.2017 / 06:33

1 answer

2

First, you can open all 3 files simultaneously using with , like this:

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

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

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

And after that, put all of them 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)
    
06.10.2017 / 07:00