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

后端 未结 3 1469
轻奢々
轻奢々 2021-01-21 22:41

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:

3条回答
  •  一整个雨季
    2021-01-21 22:57

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

提交回复
热议问题