Manipulating python text files

Asked

Viewed 1,588 times

0

I know it is not possible to write to a file I open in read mode, but I was wondering if it is possible to read the lines of a file I open for writing, after having written on it?

1 answer

1

The file needs to be opened using the mode wr+, which allows read and write operations via the file descriptor,

You can use the method seek() descriptor to return the file cursor to the beginning, see only:

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())

Exit:

alpha
beta
gamma
delta

Browser other questions tagged

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