How to add text to a specific line in Python txt file?

Asked

Viewed 1,231 times

3

I am trying to store data in a txt file, but I need to save it in specific lines. How to proceed?

I’d like to do something like:

data = open('arquivo.txt', 'a')
data[linha específica].write('Texto desejado')
data.close()
  • You could just record " n"s up to the line you want, and then write your text.

  • So, G. Bittencourt, the problem is that the text has "busy" lines that cannot be replaced until the desired line. I’m making some sort of text lists.

  • Oh yes, I’m sorry, I didn’t understand it that way.

2 answers

3

First you need to separate each line from your file. To do this, use the method readlines which will give you a list of all the separate lines.

After that, simply insert the text you want with the method into the list insert and write lines inside the list with the method writelines. Take the example:

linha_especifica = 1
texto = "<SEU TEXTO>"

file = open('arquivo.txt', 'r')
lines = file.readlines()
file.close()

lines.insert(linha_especifica, texto + "\n")

file = open('arquivo.txt', 'w')
file.writelines(lines)
file.close()
  • Thanks, Jean! I didn’t have the insight to write the lines again in the file. Thanks :D

2


To another answer suggests that you upload the entire file to memory (as that is what readlines() do), and then write all the lines again in the same file. It may even work and give no problem in most cases, but there are two reasons why:

  • if the file is too large, it will be wasting memory for nothing (it may even burst, depending on the size and the amount of files being processed)
  • when rewriting all lines again in the same file, there is a risk of corrupting it if any error occurs in the middle of writing (suppose the file has 1000 lines and when writing gives an error in the third, the file will get corrupted, with the lines 3 to 1000 missing)

For the first problem, just go through the file line by line. And for the second problem, just create a temporary file, write to it and at the end - only if all goes well - rename it to the original file. Thus, if any error occurs while writing, only the temporary file will get corrupted (and has no problem because it is temporary even), but the original file will remain intact.

Then it would look like this:

import shutil, tempfile

def incluir_linha(nome_arquivo, numero_linha, conteudo):
    with open(nome_arquivo) as orig, \
         tempfile.NamedTemporaryFile('w', delete=False) as out:
        for i, line in enumerate(orig): # percorre o arquivo linha a linha
            if i == numero_linha - 1:
                out.write(f'{conteudo}\n')
            out.write(line)

    shutil.move(out.name, nome_arquivo)

# incluir o texto "xyz" na terceira linha do arquivo
incluir_linha('arquivo.txt', 3, 'xyz')

Based on: How to Edit a file in-place

I used with to open the files as this ensures that they will be closed at the end (even in case of error, which does not happen when you call close() directly - unless it is a block finally).

Then I use enumerate to go through the lines of the file at the same time I get the respective number from it. The detail is that the index starts from scratch, so the first line is zero, the second line is 1, etc (so no if I subtract 1 from numero_linha).

I also use the module tempfile to create the temporary archive and shutil.move to rename the file at the end.

Browser other questions tagged

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