how to find and change a specific python line?

Asked

Viewed 6,889 times

4

I’m learning Python and I’ve been creating txt files, adding things and rewriting them but n managed to modify a specific line, how can I do this?? and also I wanted to know how to find out on which line a string specifies this, I can already search but n managed to make the program find the line where the string is :|

to search I enstou using...

palavra = input('palavra a pesquisar ')
for line in open('perfil.txt'):
    if palavra in line:
        print(line)

2 answers

3

To replace a particular row of 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 number of the line counted from 0; nova_line is a string of the contents of the new line.

To find which line is a string 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 doubt, comments there.

  • 1

    Benedito, just a small repair, texto.index(i) failure if there are equal lines, the function will only fetch the first occurrence, you can do: for line_num, i in enumerate(texto): ... print(line_num)

  • Or just replace the content in the list texto, generated by readlines() at the desired position (plus 1, since the numbering of lines in a file starts at 1, while the list indexes start at 0).

1

path = 'C:\\seu_Diretorio\\'                       # Caminho do diretorio
files = [
            f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))
        ]                                          # Varrendo cada arquivo
filesLen = len(files)                              # Pegando o numero de arquivos do diretorio
dataAtual = datetime.datetime.now()
one_days_ago = dataAtual - datetime.timedelta(days=1)
y = 1
for x in range(filesLen):                          # Repetindo o loop de acordo com a quantidade de arquivos
    print(f'=====INICIO DA LEITURA DO ARQUIVO {files[x]} ============')
    f = open(f'{path}{files[x]}', 'r')             # Abrindo o arquivo
    linhas = f.readlines()                         # Pegando cada linha do arquivo.txt e jogando dentro de um array
    z = linhas[0].replace(
        linhas[0][15:23], dataAtual.strftime('%d%m%Y')
    )                                              ## Substituindo a primeira linha
    with open(f'{path}{files[x]}', 'w') as f:      # Abrindo o arquivo para poder escrever/modificar a linha
        for i, line in enumerate(linhas, 1):       # O 'i' é o indice da linha o line é a linha
            if i == 1:                             # Se o indice da linha for igual a 1 ele ira executar esse bloco
                f.writelines(z)
                print('A linha escolhida foi modificada')
            else:                                  # Senao ira executar este
                f.writelines(line)

**There are some unnecessary things in the code with for example the variables: dataAtual, one_days_ago, z (this variable was used to replace the line I chose, change it to the line you want and if you wanted to choose the input of the letter you want to change), with this code I was able to change the first line of my file and tbm the word in the middle of the string, hopefully it can be useful for Voce tbm **

Browser other questions tagged

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