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()
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()
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:
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 python txt
You are not signed in. Login or sign up in order to post.
You could just record " n"s up to the line you want, and then write your text.
– G. Bittencourt
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.
– Bruno Kenzo
Oh yes, I’m sorry, I didn’t understand it that way.
– G. Bittencourt