I know I can not write to a file that I open in read mode, but I wanted to know if I can read the lines of a file that I open to writing, after writing it ?
I know I can not write to a file that I open in read mode, but I wanted to know if I can read the lines of a file that I open to writing, after writing it ?
The file needs to be opened using wr+
mode, which allows read and write operations through the file descriptor,
You can use the seek()
method of the descriptor to return the file cursor to the start, see:
lista = ['alpha','beta','gamma','delta']
with open("texto.txt", "wr+") as arq:
# Grava cada elemento da lista como uma linha no arquivo
for i in lista:
arq.write(i + "\n" )
# Retorna cursosr para o inicio do arquivo
arq.seek( 0, 0 )
# Le as linhas do arquivo a partir do
for linha in arq:
print(linha.strip())
Output:
alpha
beta
gamma
delta