add text to the beginning of my text file

0

I was trying to add text to a text file at the beginning but it always puts it at the end. My question is how could I make the text that I add, in python, add it to me at the beginning and not at the end? I will have a text file, eg:

Mifichero.txt

Then I wanted to put text at the beginning so that.

  

The new text that I will write in my file

Any possible way to put the text at the beginning using python?

    
asked by Sergio Ramos 09.03.2018 в 00:07
source

1 answer

2

Depends on how the file is being opened according to a,w,a+,r.. to write before you can use the r+ option in a function like this:

def primeralinea(archivo, nuevotexto):
    with open(archivo, 'r+') as f:
        contenido = f.read()
        f.seek(0, 0)
        f.write(nuevotexto.rstrip('\r\n') + '\n' + contenido)

primeralinea('Mifichero.txt','textonuevo')
    
answered by 09.03.2018 в 00:25