how to find and change a specific line python?

2

I'm learning Python and I've been creating txt files, adding things and rewriting them but I have not been able to modify a specific line, how can I do that? and I also wanted to know how to find out what line a string specifies this, I can already search but I could not make the program discover the line where the string is: |

To search I've uploaded using ...

palavra = input('palavra a pesquisar ')
for line in open('perfil.txt'):
    if palavra in line:
        print(line)
    
asked by anonymous 24.01.2017 / 06:14

1 answer

1

To replace a certain line in a file, you can use this function:

def alterar_linha(path,index_linha,nova_linha):
    with open(path,'r') as f:
        texto=f.readlines()
    with open(path,'w') as f:
        for i in texto:
            if texto.index(i)==index_linha:
                f.write(nova_linha+'\n')
            else:
                f.write(i)

Where: path is a string with the name of the file you want to change; index_line is the line number counted from 0; new_line is a string of the contents of the new line.

To find what line a string is on, you can use this function:

def encontrar_string(path,string):
    with open(path,'r') as f:
        texto=f.readlines()
    for i in texto:
        if string in i:
            print(texto.index(i))
            return
    print('String não encontrada')

Where string is the string you want to find. Any questions, please comment.

    
24.01.2017 / 06:37