简体   繁体   English

如何替换/更改txt.file中的元素

[英]How to replace/change element in txt.file

Im trying to replace a cetain element in a txt file. 我正在尝试替换txt文件中的cetain元素。 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. 假设如果我在telephonelist.txt中找到该名称,我希望我使用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. 让我们说name = Jens,然后我希望它返回99776612这是Jens的tlf数字,然后输入'newNumber'将替换这个数字。 i am new to python. 我是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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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