How to change a specific line in a file, depending on chosen name?

Viewed 108

I have a text file where i have numbers and names listed. each number belongs to a specific name, and they belong on the same line. the content of the file, looks like this:

Kari 98654321
Liv 99776655
Ola 99112233
Anne 98554455
Jens 99776612
Per 97888776
Else 99455443
Jon 98122134
Dag 99655732
Siv 98787896

(NOTE* the names and numbers are seperated by a new line, it just pastes everything on the same in here for some reason) Lets say i choose "Else" as the chosen name, i want to be able to update the file and change the chosen person's number with a new chosen number

I am not that experienced in python, so i am sturggling quite much with finding solutions for this problem, but ive tried using .replace(), .readline() and other functions to replace the content with something else, but i just keep replacing the entire file

import os
def endreNummer():
    with open("hei.txt", "a+"):

endreNummer()

the expected output if i chose "Kari" as name, and "1881" as the new number. the output would look like this:

Kari 1881
Liv 99776655
Ola 99112233
Anne 98554455
Jens 99776612
Per 97888776
Else 99455443
Jon 98122134
Dag 99655732
Siv 98787896
3 Answers

Here you go, this should do it.

As Mateen Ulhaq mentioned in the comments, there is no reasonable way of doing this without rewriting the whole file so this solution includes just that. However it rewrites the file only if the choosen name is found withing initial file.

Also this does not handle cases when input number isn't really a number so in case someone inputs notnumber123 as the choosen number it would still get written to the file.

filepath = 'hei.txt'

choosen_name = input('Choose name: ')
choosen_num = input('Choose number: ')

with open(filepath) as f:
    content = f.readlines()

file_changed = False
new_content = []
for line in content:
    if choosen_name in line:
        new_content.append('{} {}\n'.format(choosen_name, choosen_num))
        file_changed = True
    else:
        new_content.append(line)

if file_changed:
    with open(filepath,'w') as f:
        for line in new_content:
            f.write('{}'.format(line))
else:
    print('Choosen name not found.')

It seems a dictionary would idealy suit the case. I would try this:

names_dictionary = dict()
f = open("hei.txt", "r")
for name, number in zip(f, f):
    names_dictionary[name] = number

to update any number simply:

names_dictionary[name] = any_number

As some of the comments suggested, you can't acces specific lines of a textfile. The approaches you have tried so far, do replace text in strings, like you want, but the string you are modifying don't have any link to the file anymore.

You have to read your hole file in memory instead. Make your desired changes, and then write everything back to the file.

lines = []
with open("MyFile.txt", 'r')as MyFile:
    for line in MyFile.readlines():
        lines.append(line)

for index, line in enumerate(lines):
    if line.startswith("Kari"):
        lines[index] = "Kari 1881\n"

with open("MyFile.txt", "w+") as MyFile:
    MyFile.writelines(lines)

This example works for this specific case. I'll leave the challenge of generalizing it up to you.

Related