Doubt about inserting content from a .txt file into a list

0

I have a question about inserting the contents of a text file into a list in python.

I want to put the first line of a text file in a list. In my code it runs the task but the following message appears:

[<_io.TextIOWrapper name='lista2.txt' mode='w' encoding='cp1252'>].

Below is my code:

print ("-"*50)
print ("-"*50)

itens = []
item=1
arquivo = open('lista.txt','w')

with open ('lista.txt') as f1:
    conteudo = f1.read()

with open ('lista2.txt','w') as f2:
    f2.write(conteudo[::-1])
    itens.append(f2)

print (itens)

print ("-"*50)
print ("-"*50)
    
asked by anonymous 05.11.2018 / 12:29

2 answers

0
The open method opens the file and returns a TextIOWrapper object, but does not read the contents of the files.

To actually get the contents of the file, you need to call the read method on this object, like this:

G = open(P, 'r')
print(G.read())

However, you should be careful to close the file by calling the close method on the file object or using as you did: with open (. ..) , using syntax that will ensure that the file is closed properly, as follows:

with open(P, 'r') as G:
    print(G.read())

So you do not have to use this command before: file = open ('list.txt', 'w')

print ("-"*50)
print ("-"*50)

itens = []
item=1

with open ('lista.txt') as f1:
    conteudo = f1.read()

with open ('lista2.txt','w') as f2:
    f2.write(conteudo[::-1])
    itens.append(f2)


print ("-"*50)
print ("-"*50)

This were in the file list2.txt gets inverted the elements of the list.txt

    
05.11.2018 / 13:11
0

By focusing directly on what was asked, it turns out that what is written in the list is the object representing the file access, f2 :

with open ('lista2.txt','w') as f2:
    f2.write(conteudo[::-1])
    itens.append(f2) # <-- aqui escreve f2 e não o conteudo

And this object is actually a TextIOWrapper as you see in the output shown. In addition, you are writing in the file the inverted content using slicing with [::-1] .

However you start by opening the file you want to read as written, with w , and this ends up cleaning up all the contents of it immediately, in this line:

arquivo = open('lista.txt','w') # ao abrir inicialmente como 'w' limpa o conteudo

This line should be removed at all.

Then read reads the whole file, but if you only want the first line, you should use readline which is more direct and simple.

So the code you have can be rewritten like this:

print ("-"*50)
print ("-"*50)

with open ('lista.txt', 'r') as f1:
    conteudo = f1.readline()

itens = []    
with open ('lista2.txt','w') as f2:
    f2.write(conteudo)
    itens.append(conteudo)

print (itens)
print ("-"*50)
print ("-"*50)
    
05.11.2018 / 13:05