Why doesn’t he run my read() since I opened it for reading and writing at the same time

Asked

Viewed 56 times

0

The code below allows me to write, but does not show me the content of what I wrote in the file with the read method()

filename = input('Informe o nome do arquivo: ')

filename += '.txt'

arquivo = open(filename,'w+')

arquivo.write(input('O que deseja escrever?: '))

arquivo.read()

arquivo.close()

1 answer

0


You must use the method seek to move the cursor to the first position before running the read.

filename = input('Informe o nome do arquivo: ')

filename += '.txt'

arquivo = open(filename,'w+')

arquivo.write(input('O que deseja escrever?: '))

# Voltar para a posição inicial
arquivo.seek(0)

# O método read() retorna o conteúdo do arquivo 
conteudo = arquivo.read()

# Printar no terminal o conteúdo do arquivo
print(conteudo)

arquivo.close()
  • Thanks Friend, I thought that if I just typed file.read() it would already plot the contents of the file on the screen without necessarily needing print(). As for the use of Seek really made all the difference, but I didn’t use it because I had read that when using the parameter 'w+' it points the cursor to the beginning of the file.

  • @Alissonjonathan When you use w+ it really points to the beginning of the file. The point is that when you use write() the cursor moves forward, so when you call read() the cursor is after the written text, so you should use Seek() to return the cursor to the initial position.

Browser other questions tagged

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