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:
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.')