Change text in file with Python

前端 未结 4 496
忘了有多久
忘了有多久 2020-12-22 14:17
def false_to_true():
    name = input(\"Input name: \")
    file=open(\"users.txt\",\"r\")
    lines = file.readlines()
    file.close()
    for line in lines:
              


        
4条回答
  •  隐瞒了意图╮
    2020-12-22 14:50

    To modify a text file inplace, you could use fileinput module:

    #!/usr/bin/env python3
    import fileinput
    
    username = input('Enter username: ').strip()
    with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
        for line in file:
            if line.startswith(username + "/"):            
                line = line.replace("/False", "/True") 
            print(line, end='')
    

    See How to search and replace text in a file using Python?

提交回复
热议问题