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

Asked

Viewed 41 times

0

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

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

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

Below follows 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)

2 answers

0

Focusing directly on what was asked, it turns out that what is written in the list is the object that represents the access to the file, the 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 seen in the output shown. In addition, you are writing the content inverted through slicing with the [::-1].

However you start by opening the file you want to read as written, with w, and that ends up wiping all of its contents right away, on this line:

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

This line must be removed at all.

Then the read reads the whole file, but if you only want the first line, you should use the readline that 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)
  • Thanks. Helped me a lot. Thanks.

0


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

To really get the contents of the file, you need to call the method read in that object, thus:

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

However, you should take care of closing the file by calling the method close-up in the file object or using as you did usand:the 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 don’t need 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 was in the file Lista2.txt is reversed the elements of the list.txt

Browser other questions tagged

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