简体   繁体   中英

How to replace/change element in txt.file

Im trying to replace a cetain element in a txt file. let say that if i find the name in telephonelist.txt, i want i to change the number to this person with the input value of newNumber. let's say that name = Jens, then i want it to return 99776612 that is the tlf number to Jens, and then the input of 'newNumber' will replace this number. i am new to python.

def change_number():
while True:
    try:
      name = input('Name: ') #Enter name
      newNumber = input('New number: ') # Wanted new number
      datafile = open('telephonelist.txt')

      if name in open('telephonelist.txt').read():
        for line in datafile:
          if line.strip().startswith(name):
            line = line.replace(name,newNumber)
            print('I found', name)
            quit()
      else:
        print('I could not find',name+',','please try again!\n')
        continue
    except ValueError:
      print('nn')
change_number()



This i telephonelist.txt

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

Load content, modify it, seek to beginning of the file, write the modified content again and then truncate the rest.

def change_number():
    name = input('Name: ') #Enter name
    newNumber = input('New number: ') # Wanted new number
    with open('telephonelist.txt', 'r+') as file:
        data = file.read().splitlines()
        data = [line if not line.split()[0] == name else f"{name} {newNumber}" for line in data]
        file.seek(0)
        file.write("\n".join(data))
        file.truncate()

change_number()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM