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